简体   繁体   English

如何通过点击第一个按钮将第二个按钮传递给javascript函数

[英]how to pass second button on click over the first button to a javascript function

I am new to javascript and html . 我是javascript和html的新手。 I have a small question. 我有一个小问题。 I have some thing like the following in the javascript file. 我在javascript文件中有以下内容。

function setColor(btn, color)
{
if (btn.style.backgroundColor == "#f47121") {
    btn.style.backgroundColor = color;
} else {
    btn.style.backgroundColor = "#f47121";
}
}

<input type="submit" value="Review & Next" name="b1" onclick="setColor(this,'#fff200');" />
<input type="submit" value="1" name="b2" />

my question is how to pass the second button as function argument when click the first button instead of 'this' i use b2 ,but it not worked can anyone help please 我的问题是如何将第二个按钮作为函数参数传递时单击第一个按钮而不是'this'我使用b2,但它没有用,任何人都可以帮助请

You could use the id instead. 你可以改用id。

set the id to 'b2' and then inside the function find it and set it. 将id设置为'b2',然后在函数内找到并设置它。 You no longer have to use this anymore .. whatever id you pass in the function will use that instead. 你不再需要再使用this了......无论你在函数中传递的id是什么,都会使用它。

<input type="submit" value="Review & Next" name="b1" id="b1" onclick="setColor('b2','#fff200');" />
<input type="submit" value="1" name="b2" id="b2"/>

You can now pass any of them to the function 您现在可以将它们中的任何一个传递给该函数

function setColor(arg, color)
{
   var btn = document.getElementById(arg);

if (btn.style.backgroundColor == "#f47121") {
    btn.style.backgroundColor = color;
} else {
    btn.style.backgroundColor = "#f47121";
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM