gpt4 book ai didi

Javascript onclick 对象相关方法

转载 作者:行者123 更新时间:2023-11-28 02:31:56 25 4
gpt4 key购买 nike

我得到了一个可以切换 onclick 功能的图像。调用的函数是对象的方法。我的问题:我不知道对象的名称,所以我该怎么办

初始 HTML 代码:

<img id="someID" [...] onClick="someObject.aFunction();" />

想要的结果:

<img id="someID" [...] onClick="someObject.otherFunction();" />

我当前的 Javascript(解决方法):

someClass.prototype.aFunction() = function() {
button = document.getElementByID('someID');
button.setAttribute("onclick", button.getAttribute('onclick').split('.')[0]+'.otherFunction()');
}

不太好,但目前可以用。还有更好的解决方案吗?

最佳答案

这是一种可能的解决方案:

var el = document.getElementById('someID');
el.onclick = function(){
// or some other prop
if(el.hasBeenClicked)
function1();
else
function2();

// toggle the selected state
el.hasBeenClicked= !el.hasBeenClicked;
}

当然,还有很多(更好的)解决方案。
如果你使用jquery,那么代码应该被翻译成类似这样的内容:

$('#someID').toggle(function1, function2);

关于Javascript onclick 对象相关方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014868/

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