gpt4 book ai didi

javascript - 使用 jQuery 设置元素的 onclick 属性时遇到问题

转载 作者:行者123 更新时间:2023-12-02 23:16:27 25 4
gpt4 key购买 nike

我的网页上有一些元素共享类名“table-data”。我试图循环遍历它们并给每个它们一个唯一的 id,然后我希望它们都具有相同的 onclick 属性。我能够使用纯 JavaScript 成功地为它们每个人提供一个唯一的 id,但我遇到问题的部分是为它们提供相同的 onclick 属性。我尝试使用 JavaScript 和 jQuery,但都失败了。

这是我的代码:

// this counter will be used to give each element a unique id
var counter = 0;

// x holds all elements with the class name "table-data"
var x = document.getElementsByClassName("table-data");

// loop through all the elements in the array x
for (var i = 0; i < x.length; i++) {

// give each element the name "idNum" plus whatever number the counter variable holds
var idName = 'idNum' + String(counter);

// set the id name to the variable defined above
x[i].setAttribute('id', idName);

// here is the part I am struggling with, this section is supposed to alert the id of the element when it is clicked
$('#' + idName).click(function () {
alert(idName);
});

// increment the counter
counter += 1;

我遇到的问题是所有元素都显示数组“x”中最后一个元素的 idName。因此,如果总共有 5 个元素,并且我对它们运行此代码,则单击时它们都会显示第 5 个元素的 idName。我尝试在 onclick 函数之外对 idName 进行alert() 操作,这样循环就会在每个元素的 idName 被分配后立即发出警报,并且效果很好。我会为五个不同的元素获得五个不同的 id,那么是什么导致了 onclick 函数内部的问题呢?

我还尝试了以下方法,但也不起作用:

x[i].setAttribute('onclick', 'call_alert(this.idName)');

function call_alert(clickedId) {
alert(clickedId);
}

我对网络编程非常陌生,所以如果我的代码中有任何明显的错误,我很抱歉。

最佳答案

你让事情变得比你需要的复杂得多。您不需要为每个元素添加 id,您可以简单地使用 class(.) selector 绑定(bind)到一个类上。然后一次性添加点击绑定(bind):

$(document).ready(function() {
//match on the class
$('.table-data').click(function(){
//access the actual element clicked using $(this)
alert('clicked'+ $(this).text());
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="table-data">1</a>
<a href="#" class="table-data">2</a>

关于javascript - 使用 jQuery 设置元素的 onclick 属性时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57145821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com