gpt4 book ai didi

javascript onClick=funct(this) 使用 addEventListener 替换

转载 作者:行者123 更新时间:2023-12-03 10:06:23 25 4
gpt4 key购买 nike

我正在寻找旧的 onClick=funct(this) 的明确替代品动态生成代码时的 html 事件处理程序。问题是我怎么看都找不到。

我正在创建一个 <div>标签作为函数的一部分,其内部是 <a>标签带有 onClick 的 html 事件处理程序,它将自身作为参数传递,以便我可以在其 <div> 中找到相关元素。 。但我知道现在这是不好的做法,我想改用首选的 addEventListener 方式,但我不知道如何将调用者传递到函数中,除非因为据我所知以下内容不起作用。

renamehead.addEventListener('click', 'rename(renamehead)');

我当前的代码:js,以及它生成的html。

function makeActivity(name) {
var act = document.createElement('div');
act.setAttribute('class', 'activity');
var acthead = document.createElement('div');
acthead.setAttribute('class', 'acthead interface_element');
act.appendChild(acthead);

namehead = document.createElement('h3');
var txt = document.createTextNode(name);
namehead.appendChild(txt);
namehead.setAttribute('contenteditable', 'true')
acthead.appendChild(namehead);

var renamehead = document.createElement('a');
txt = document.createTextNode('Rename');
renamehead.appendChild(txt);
renamehead.setAttribute('class', 'headcommand');
renamehead.setAttribute('href', 'javascript:void(0)');
renamehead.setAttribute('onClick', 'rename(this)');

var delhead = document.createElement('a');
txt = document.createTextNode('Delete');
delhead.appendChild(txt);
delhead.setAttribute('class', 'headcommand');
delhead.setAttribute('href', 'javascript:void(0)');
delhead.setAttribute('onClick', 'delActivity(this)');

txt = document.createTextNode(' ');
acthead.appendChild(renamehead);
acthead.appendChild(txt);
acthead.appendChild(delhead);

var actions = document.createElement('div');
actions.setAttribute('class', 'actactions');
actions.appendChild(makeDropDiv());
act.appendChild(actions);
return act;
}
<div id="activitydiv">
<div class="activity">
<div class="acthead interface_element">
<h3>Record</h3>
<a href="javascript:void(0)" onclick="rename(this)">Rename</a>
<a href="javascript:void(0)" onclick="delActivity(this)">Delete</a>
</div>
</div>
<div class="activity">
<div class="acthead interface_element">
<h3>Stop</h3>
<a href="javascript:void(0)" onclick="rename(this)">Rename</a>
<a href="javascript:void(0)" onclick="delActivity(this)">Delete</a>
</div>
</div>
</div>

最佳答案

传入真实函数,您可以简单地使用局部变量。

renamehead.addEventListener('click', function() {
rename(renamehead);
});

您确实不想将要执行的字符串传递给addEventListener。传入真正的 JavaScript 函数将为您提供所需的灵 active 。

关于javascript onClick=funct(this) 使用 addEventListener 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30335967/

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