Javascript 如何使用jQuery通过id从元素中获取html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14593727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get html from element by id with jQuery
提问by Lukas
I have simple list:
我有一个简单的清单:
<ul id="tabs_nav">
<li id="t_00">data</li>
<li id="t_01">data</li>
<li id="t_02">data</li>
<li id="t_03">data</li>
</ul>
Now: How do I get the html of the first element, depending on what is ID. I would add that all of ID's change dynamically with the click of the button. This is my code:
现在:如何获取第一个元素的 html,具体取决于 ID 是什么。我想补充一点,所有的 ID 都会随着按钮的点击而动态变化。这是我的代码:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
Thx for help.
谢谢你的帮助。
回答by Nope
Seems you are missing the id selector #.
似乎您缺少 id 选择器#。
You are trying to get the html from the selector:
您正在尝试从选择器中获取 html:
ladder_nav_tabs.find(first_ladder_element_inset_id).html();
This won't work as an id selector needs the #. Like this:
这将不起作用,因为 id 选择器需要#. 像这样:
ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
Try the following to fix your code:
尝试以下操作来修复您的代码:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
DEMO- Updating to valid id selector syntax
演示- 更新到有效的 id 选择器语法
Alternatively you could shorten your code using jQuery's eq, similar to this:
或者,您可以使用 jQuery 的eq缩短代码,类似于:
btn.on('click',function(){
var theHtml = $('#tabs_nav li').eq(0).html();
console.log(theHTML);
});
回答by Niet the Dark Absol
Don't use jQuery purely as a selector engine:
不要将 jQuery 纯粹用作选择器引擎:
btn.onclick = function() {
console.log(document.getElementById('tabs_nav').children[0].innerHTML);
};
回答by Kyle
回答by Alessandro Minoccheri
Try this:
尝试这个:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li:first-child').attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
You have tou use :first-child
你必须使用 :first-child

