简体   繁体   中英

change onclick function of the button dynamically using javascript

How can I change onclick behavior of button dynamically using javascript?

Here is what I meant:

I have following buttons:

<button class="num" onclick="getval(0)">0</button>
<button class="num" onclick="getval(1)">1</button>
<button class="num" onclick="getval(2)" >2</button>
<button class="num" onclick="getval(3)" >3</button>

function getval(){

...............

}

function getvalNew(){

..............

}

How can I make the buttons to switch from getval() to getvalNew() and reset it again?

function getval() {
    ........
    var buttons = document.getElementsByClassName("num");
    for (i=0;i<buttons.length;i++){
        buttons[i].onclick = function(){
            getvalNew();
        }
    }
}

And vice versa for the other function. At least, this should work....

you can do something like this:

code

$(".num").on("click", function () {
    if ($(this).hasClass("getval")) {
        $(this).removeClass("getval").addClass("getvalnew");
        //do what you need here 
        alert("getVal");
    } else {
        $(this).removeClass("getvalnew").addClass("getval");
        //do what you need here 
        alert("getValNew");
    }
});

FIDDLE

http://jsfiddle.net/ygqrU/

You can do this with single liner JQuery syntax with your conditional statements when you want to change the function mapping.

//bind all
$('.num').bind('click', getValNew());

//Unbind all
$('.num').unbind('click');

Here's an approach, based on my blank.html template.

Note: in setAllFunc3, you could attach several handlers to the one element. You can also remove them selectively. See another member's note about getAllByClassName.

Also note: by attaching the handler, we get access to the this var. This means we know which element triggered the call. I have simply extracted the text from the button. You could instead get the value for an attribute, that you then use in the handler. Probably something for you to discover a little later. :)

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(element, newStr)
{
    index=element.className.indexOf(newStr);
    if ( index == -1)
        element.className += ' '+newStr;
    else
    {
        if (index != 0)
            newStr = ' '+newStr;
        element.className = element.className.replace(newStr, '');
    }
}
function forEachNode(nodeList, func)
{
    var i, n = nodeList.length;
    for (i=0; i<n; i++)
    {
        func(nodeList[i], i, nodeList);
    }
}

window.addEventListener('load', mInit, false);

function mInit()
{
}

function getval(inputVar)
{
    alert(inputVar + " was passed to getval");
}

function getvalNew(inputVar)
{
    alert("getvalNew(" + inputVar + ")");
}

function setAllFunc1()
{
    var tgtButtons = document.getElementsByClassName('num');
    var i, n = tgtButtons.length;
    for (i=0; i<n; i++)
        tgtButtons[i].setAttribute('onclick', 'getval(' + i + ')' );
}

function setAllFunc2()
{
    var tgtButtons = document.getElementsByClassName('num');
    var i, n = tgtButtons.length;
    for (i=0; i<n; i++)
        tgtButtons[i].setAttribute('onclick', 'getvalNew(' + i + ')' );
}

function myFunc3()
{
    var clickedBtn = this;
    var btnText = clickedBtn.innerHTML;
    alert("You clicked the button labelled: " + btnText);
}

function setAllFunc3()
{
    var tgtButtons = document.getElementsByClassName('num');
    var i, n = tgtButtons.length;
    for (i=0; i<n; i++)
    {
        tgtButtons[i].removeAttribute('onclick');
        tgtButtons[i].addEventListener('click', myFunc3);
    }
}

</script>
<style>
</style>
</head>
<body>
    <button class="num" onclick="getval(0)">0</button>
    <button class="num" onclick="getval(1)">1</button>
    <button class="num" onclick="getval(2)">2</button>
    <button class="num" onclick="getval(3)">3</button>
    <hr>
    Simple method - using attributes
    <input type='button' onclick='setAllFunc1()' value='set all to "getval()"'/>
    <input type='button' onclick='setAllFunc2()' value='set all to "getvalNew()"'/>
    <hr>
    Better method - using addEventListener
    <input type='button' onclick='setAllFunc3()' value='set all to "myFunc3()"'/>
</body>
</html>

In case the browser does not support getElementsByClassName, this is an alternative:

var elems = document.getElementsByTagName('button');
for (i=0;i<elems.length;i++) {
    if(elems[i].className == "num") {
        elems[i].onclick = function(){
        getvalNew();
    }
}

Maybe something like this:

.

var button = document.getElementsByClassName("num")
// You could also do: var button = document.getElementsByTagName("button")

function set() { // Change all the buttons onclick event to getvalNew
    for (i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            getvalNew(i)
        }
    }
}

function reset() { // Change all the buttons onclick event back to getval
    for (i = 0; i < button.length; i++) {
        button[i].onclick = function() {
            getval(i)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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