如何使用jQuery从id获取html [英] How to get html from element by id with jQuery
本文介绍了如何使用jQuery从id获取html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有简单的清单:
<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>
现在:我如何获取第一个元素的html,具体取决于ID。我想补充说,只需点击按钮,所有ID都会动态变化。这是我的代码:
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:
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求助。
推荐答案
似乎你错过了id选择器#
。
Seems you are missing the id selector #
.
你试图得到选择器中的html:
You are trying to get the html from the selector:
ladder_nav_tabs.find(first_ladder_element_inset_id).html();
这不起作用,因为id选择器需要#
。像这样:
This won't work as an id selector needs the #
. 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 - 更新为有效的ID选择器语法
DEMO - Updating to valid id selector syntax
或者你可以使用jQuery的 eq ,类似于:
Alternatively you could shorten your code using jQuery's eq, similar to this:
btn.on('click',function(){
var theHtml = $('#tabs_nav li').eq(0).html();
console.log(theHTML);
});
这篇关于如何使用jQuery从id获取html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文