gpt4 book ai didi

javascript - 将选择器 $(this) 传递给函数的简单方法

转载 作者:太空宇宙 更新时间:2023-11-04 13:58:23 26 4
gpt4 key购买 nike

我有几个动态创建的 <div>带有数据属性,我附加到另一个 <div>像这样:

var jobtypehtml = "";

for (var i = 0; i < arrayLength; i++) {

jobtypehtml += `<div class="jobtypeselect" data-jobtypechecked="0" onClick="check()"></div>`;

}

$('#jobtype').append(jobtypehtml);

点击 <div>检查功能被调用,看起来像这样:

function check(){

alert($(this).getAttribute('data-jobtypechecked'));

}

如您所见,我想获得被点击的 <div> 的数据属性.我看到了一些使用 .call 和 .apply 的解决方案,但这对我来说似乎很复杂。有没有更简单的方法来实现它?

编辑:

function check(){

alert($(this).data('jobtypechecked'));

}

上面的函数警告“undefined”。

最佳答案

您可以像这样将 this 传递到调用站点的点击函数中:

var jobtypehtml = "";

for (var i = 0; i < arrayLength; i++) {

jobtypehtml += `<div class="jobtypeselect" data-jobtypechecked="0" onClick="check(this)"></div>`;

}

$('#jobtype').append(jobtypehtml);


function check(elm){

alert($(elm).getAttribute('data-jobtypechecked'));

}

关于javascript - 将选择器 $(this) 传递给函数的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56652128/

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