问题
<div class="myclass">
<ul>
<li><a> first node <i>textContent</i></a></li>
<li><a>textContent1</a></li>
<li><a>textContent2</a></li>
<li><a>textContent3</a></li>
</ul>
</div>
JS
$(".myclass ul li").live("click", function() {
alert(this.textContent);
});
I wish to get the value of <a>
element using onclick
and first <li>
I wish to get the value of <i>
element.
Is it possible?
回答1:
use text()
:
$(document).on("click", ".myclass ul li", function() {
var txt = $('i', this).length ? $('i', this).text() : $(this).text();
alert( txt );
});
FIDDLE
Also, live()
has been deprecated and removed, and to get the text of the i element if such an element exists, you check if exists and the act appropriately
来源:https://stackoverflow.com/questions/18387430/onclick-get-this-textcontent-of-an-element