onclick get this textContent of an element

▼魔方 西西 提交于 2021-02-11 14:26:36

问题


<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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!