[英]How to get html from element by id with jQuery
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. 现在:我如何获取第一个元素的html,具体取决于ID。 I would add that all of ID's change dynamically with the click of the button. 我想补充说,只需点击按钮,所有ID都会动态变化。 This is my 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);
});
Thx for help. 谢谢你的帮助。
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 #
. 这不会起作用,因为id选择器需要#
。 Like this: 像这样:
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 DEMO - 更新为有效的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);
});
Don't use jQuery purely as a selector engine: 不要将jQuery纯粹用作选择器引擎:
btn.onclick = function() {
console.log(document.getElementById('tabs_nav').children[0].innerHTML);
};
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.