使用Javascript添加OnClick事件无效

时间:2017-03-21 19:38:37

标签: javascript jquery

我正在尝试使用JavaScript添加onclick事件。

$.getJSON(api , function(data) {
    //First Option found (not working)
    //document.getElementById("today_button").SetAttrribute("onclick", "window.location.replace('" + data[1] + "')");

    //Second Option found (not working either)
    document.getElementById('today_button').onclick = "window.location.replace('" + data[1] + "');";
});

存在变量,事件被触发,传输的数据是正确的,除此之外的所有内容都可以正常工作(比如更改此按钮的禁用状态)。

我希望你能帮助我

3 个答案:

答案 0 :(得分:2)

您需要为onclick分配一个函数,而不是字符串:

document.getElementById('today_button').onclick = function(event) {
   window.location.replace(data[1]);
}

答案 1 :(得分:0)

为什么要将字符串指定为单击处理程序?只需使用一个功能。

document.getElementById('today_button').onclick = function () {
    location.replace(data[1]);
};

答案 2 :(得分:0)

问题是你为onclick指定了字符串,但它需要函数。

document.getElementById('today_button').onclick = function() {
    window.location.replace(data[1]);
}
相关问题