简体   繁体   English

Onclick事件对特定按钮起作用

[英]Onclick event act on specific button

I have a function called changeImage and I would like to change only the button I have clicked. 我有一个名为changeImage的函数,我想只更改我点击的按钮。
How can I achieve that? 我怎样才能做到这一点? I don't think that hard code is the solution. 我不认为硬代码是解决方案。 I am using PHP and javascript. 我正在使用PHP和JavaScript。 *I have about 100 buttons and each one has its own ID eg: A1,A2,B1,B2 *我有大约100个按钮,每个按钮都有自己的ID,例如:A1,A2,B1,B2

my code: 我的代码:

<script type="text/javascript">
        function changeImage() {
            var image = document.getElementById('A1');
            if (image.src.match("Grey")) {
                image.src = "Image/Yellow.png";
            } else {
                image.src = "Image/Grey.png";
                return false;
        }
    }</script>
<input id="A1" type="image" src="Image/Grey.png" onclick="changeImage()">
<input id="A2" type="image" src="Image/Grey.png" onclick="changeImage()">
<input id="B1" type="image" src="Image/Grey.png" onclick="changeImage()">
<input id="B2" type="image" src="Image/Grey.png" onclick="changeImage()">

Use this code instead : 请改用此代码:

<script type="text/javascript">
    function changeImage(e) {
        var image = e;
        if (image.src.match("Grey")) {
            image.src = "Image/Yellow.png";
        } else {
            image.src = "Image/Grey.png";
            return false;
        }
    }
</script>

<input id="A1" type="image" src="Image/Grey.png" onclick="changeImage(this)">
<input id="A2" type="image" src="Image/Grey.png" onclick="changeImage(this)">
<input id="B1" type="image" src="Image/Grey.png" onclick="changeImage(this)">
<input id="B2" type="image" src="Image/Grey.png" onclick="changeImage(this)">

So instead of calling a certain id use this command. 因此,不是调用某个id而是使用this命令。 Like if this button is clicked change its source 就像点击此按钮一样,更改其来源

   function changeImage(button) {   //button = this onclick="changeImage(button)";
        if (button.src.match("Grey")) {
            button.src = "Image/Yellow.png";
        } else {
            button.src = "Image/Grey.png";
            return false;
        }
    }

Check in JSFiddle 检查JSFiddle

Pass a variable through the function parameters, and pick it up inside the function, as exhibited here: https://stackoverflow.com/a/6575272/1864597 . 通过函数参数传递一个变量,并在函数内部获取它,如下所示: https//stackoverflow.com/a/6575272/1864597

If you don't need to pass any variables (and want to keep it cleaner), use the answer by @developer. 如果您不需要传递任何变量(并希望保持清洁),请使用@developer的答案。

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

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