我有几个span
标签,具有相同的类。每span
有它唯一的ID。现在我想获取点击的span
的内容和id类。
我知道了如何获取类(class)的 id,但我似乎无法获取 <span></span>
之间的内容标签。我试过this.html()
, this.html
, this.text
和this.tex()
但我无法获取文本。
$(".row").click(function() {
alert(this.id);
alert(this.html);
}
HTML:
<div>
<span class="row" id="1">Username of user 1</span>
<span class="row" id="2">Username of user 2</span>
<div>
最佳答案
您的 id
无效(不能以数字开头),因此请更改它们并尝试此操作
<div id="parent">
<span class="row" id="s1">Username of user 1</span>
<span class="row" id="s2">Username of user 2</span>
...
</div>
jQuery
$("#parent").on('click', '.row', function() {
alert(this.id);
alert(this.innerHTML);
});
这样做时,您将使用事件委托(delegate)
,捕获父级上的点击事件并仅定义一次处理程序(并且不会为每个span
定义昂贵的处理程序)
关于jQuery:按类获取单击的跨度的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812141/