[英]JavaScript onclick method, attach it to All Buttons
I have quite a few buttons that look like this in my html code 我的html代码中有很多看起来像这样的按钮
<li>
<span class="avatar"><span class="status online"></span></span>
<spa">
And this is my javascript function for myFunction() 这是我的myFunction()的javascript函数
var buttonState = 0;
function myFunction(){
cons
buttonState = 1;
return;
}
if(buttonState == 1){
buttonState = 0;
}
}
Since I have multiple buttons, I cant just do onclick="myFunction()" for all of them because there is no way to tell between the id of the buttons AKA they are all of ID "addFriend" so the myFunction() will always default to the first button. 因为我有多个按钮,所以我不能对所有按钮都进行onclick =“ myFunction()”,因为没有办法在两个按钮的ID之间进行区分,即它们全都是ID“ addFriend”,因此myFunction()将始终默认为第一个按钮。 There has to be a way to remedy this but i've researched it any found no good help guides. 必须有一种方法可以解决此问题,但是我已经对其进行了研究,但没有找到好的帮助指南。 Anyone have a suggestion? 有人有建议吗?
Thanks! 谢谢!
Add a "this" inside your parentheses: 在括号内添加“ this”:
<li>
<span class="avatar"><span class="status online"></span></span>
<span class="username">Barack Brobama</span>
<input type="button" id="addFriend" onclick="myFunction(this)" class="submit" value="+ Add friend">
Now do this: 现在执行以下操作:
function myFunction(pObject){
console.log(buttonState);
if(buttonState == 0){
pObject.value = 'Friend Request Pending';
buttonState = 1;
return;
}
if(buttonState == 1){
pObject.value = '+ Add Friend';
buttonState = 0;
}
}
Use this for function 使用此功能
onclick="myFunction(this)" onclick =“ myFunction(this)”
then you function will be 那么你的功能将是
function myFunction(pObject){
console.log(pObject.getAttribute('state'));
if(pObject.getAttribute('state') == '1'){
pObject.value = '+ Add Friend';
pObject.setAttribute('state', '0');
}else{
pObject.value = 'Friend Request Pending';
pObject.setAttribute('state', '1');
}
}
and sate you can save in tag 并可以保存在标签中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.