點擊我有很多有相同的標籤如下元素的元素:如何檢測從許多相同的元素
<ul>
<li>
<a>1</a>
...
</li>
<li>
<a>2</a>
...
</li>
<li>
<a>3</a>
...
</li>
...
</ul>
用戶可以點擊任何元素。我如何檢測用戶點擊的元素? (我不知道元素的數量,我可以是五個或者任何數字)。
感謝
點擊我有很多有相同的標籤如下元素的元素:如何檢測從許多相同的元素
<ul>
<li>
<a>1</a>
...
</li>
<li>
<a>2</a>
...
</li>
<li>
<a>3</a>
...
</li>
...
</ul>
用戶可以點擊任何元素。我如何檢測用戶點擊的元素? (我不知道元素的數量,我可以是五個或者任何數字)。
感謝
你可以使用this
點擊的元素。例如:
$('a').click(function(){
alert($(this).text()); //displays the clicked element's text.
});
綁定錨標記
綁定上li
$('ul li').on('click',function(){
alert($(this).text()); //This will give the text of anchor ta in your case
alert($(this).index()); //This will give you the index of li with respect to its siblings.
});
您可以使用$(this)
或this
指事件的來源。
$('a').click(function(){
alert($(this).text());
alert(this.innerText);
});
這是更好地使用class
要具體,從而使事件與預期的元素,而不是頁面上的任何一個結合。您可以將類分配給您要綁定單擊事件的元素,並使用class selector來綁定事件。
<a class="myclass">1</a>
$('.myclass').click(function(){
alert($(this).text());
alert(this.innerText);
});