te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>html - change onclick function of the button dynamically using javascript - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - change onclick function of the button dynamically using javascript - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jun 24, 2013 at 14:13 Jack_of_All_TradesJack_of_All_Trades 11.5k20 gold badges63 silver badges95 bronze badges 3
  • 2 It's easier if you don't use inline event handlers. For more information about event handling see quirksmode/js/introevents.html. – Felix Kling Commented Jun 24, 2013 at 14:15
  • 1 see @FelixKling's ment for why not to use inline event handlers, but if you have to, you could try using js to change the onclick attribute of the element. I'm a bit rusty with pure js but you could try something like jQuery('button.num').attr('onclick', 'myFunc(1)'); if you were to use jQuery. – totallyNotLizards Commented Jun 24, 2013 at 14:15
  • A simple switch statement with a different variable or array or global true falses would work. You can also just onclick do a this. and change the onclick attr to be the opposite function. – abc123 Commented Jun 24, 2013 at 14:16
Add a ment  | 

6 Answers 6

Reset to default 3

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>
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/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');

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)
        }
    }
}
发布评论

评论列表(0)

  1. 暂无评论