![](/img/trans.png)
[英]How to make an onclick in a img html5 tag call a function with a parameter?
[英]How to change the argument of a function in a onclick property on a <img> tag?
所以,我在img标签onclick中调用一个函数内联,当它执行任务时,我希望该函数调用在另一个img标签onclick属性中更改函数的第二个属性,我能想到的唯一方法是读取onclick属性的字符串,从右边扫描第一个'出现,将所有内容读到下一个'进入变量并更改它。
这是我的javascript
function hideShow(x,y) {
var hide = document.getElementById(x);
var show = document.getElementById(y);
if (!hide.classList.contains("display-none") && show.classList.contains("display-none")) {
hide.classList.add("display-none");
show.classList.remove("display-none");
} else {
hide.classList.remove("display-none");
show.classList.add("display-none");
}
}
和HTML
<img src="img/label1.png" class="cursor-pointer" onClick="hideShow('label1','label2')" id="label1">
<img src="img/label2.png" class="cursor-ponter display-none" onClick="hideShow('label2','label3')" id="label2">
<img src="img/label3.png" class="cursor-pinter display-none" onClick="hideShow('label3','label1')" id="label3">
现在我希望我知道一种更简单的方法,当我点击第三个img时,将第一个img-tags onclick-property中的函数的第二个参数更改为'label3'。
使用第二个参数的默认值创建一个全局范围的变量(对于您希望的每个图像onclick事件)。
当函数由于单击第一个图像而运行时,该函数会更改全局范围的变量。
现在,当单击第二个图像时,第二个参数具有上一个函数设置的值,或者,如果未单击第一个图像,则仍具有在创建全局范围变量时设置的默认值。
我已按预期更新了代码。
它不是在函数中传递第二个参数,而是在属性中维护,当需要点击第三个图像时,可以在函数内部更改此属性。
function hideShow(x, changeAttr) { var attrKey = 'data-element'; var hide = document.getElementById(x); var show = document.getElementById(attr(hide, attrKey)); if (!hide.classList.contains("display-none") && show.classList.contains("display-none")) { hide.classList.add("display-none"); show.classList.remove("display-none"); } else { hide.classList.remove("display-none"); show.classList.add("display-none"); } if(changeAttr) { attr(show, attrKey, x); } } function attr(elm, attrName, attrValue) { attrValue = attrValue || ''; if (elm.hasAttributes()) { var attrs = elm.attributes; for(var i = 0; i < attrs.length; i++) { if(attrs[i].name === attrName) { if(attrValue) { attrs[i].value = attrValue; } else { attrValue = attrs[i].value; } break; } } } return attrValue; }
.display-none { display: none; } .cursor-pointer { cursor: pointer; }
<img src="img/label1.png" class="cursor-pointer" onClick="hideShow('label1')" data-element="label2" id="label1"> <img src="img/label2.png" class="cursor-pointer display-none" onClick="hideShow('label2')" data-element="label3" id="label2"> <img src="img/label3.png" class="cursor-pointer display-none" onClick="hideShow('label3', true)" data-element="label1" id="label3">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.