gpt4 book ai didi

JavaScript/jQuery : How do you pass an element to a function as its 'this' ?

转载 作者:行者123 更新时间:2023-11-29 16:15:08 25 4
gpt4 key购买 nike

如何将某些内容传递给函数,就像它调用函数一样?

说我有这个功能

function ShowId() {
alert($(this).attr('id'));
}

和这个 HTML

<div id='div1'>
<a class='link'>Some link</a>
</div>

我想做这个

$('div .link').click(function() {
$(this).parent('div').call(ShowId); // What is the right syntax?
});

它应该警告:div1

最佳答案

.call()function的一个方法,所以顺序是相反的:

ShowId.call($(this).parent('div'));

不过,作为参数传递通常也是可行的:

function ShowId(elem) {
alert($(elem).attr('id'));
}
ShowId($(this).parent('div'));

关于JavaScript/jQuery : How do you pass an element to a function as its 'this' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17716993/

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