【问题标题】:On-change/click firing even though no changes where made更改/点击触发,即使没有进行任何更改
【发布时间】:2013-10-05 20:47:11
【问题描述】:

我正在尝试在选择下拉选项时触发一个函数,但我不想在 HTML 中包含内联 JavaScript。出于某种原因,当我运行脚本时,会自动注册更改/单击。为什么?

JSFiddle:http://jsfiddle.net/nysteve/QHumL/22/

var time = new Date();
var timestamp = time.toString("hh:mm:ss");

//create color from time stamp and print within div
function timeToHexColor(){
    var showlist = document.getElementById("board").innerHTML += 
                   "#" + timestamp.split(":").join("") + "<br/>";
}

//Print colors based on time interval
function Colors(interval) {
    this.interval = interval;
    switch (this.interval) {
        case 'second': 
            x = setInterval(timeToHexColor,1000);
            setTimeout(stopColors, 5000);
            break;
        case 'minute': 
            x = setInterval(timeToHexColor,60000);
            setTimeout(stopColors, 5000);
            break;       
        case 'hour': 
            x = setInterval(timeToHexColor,60000*60);
            setTimeout(stopColors, 5000);
            break;
        case 'day': 
            x = setInterval(timeToHexColor,60000*1440);
            setTimeout(stopColors, 5000);
            break;
        default: 
    }
}

//For demo purposes manually kill priting after 5 seconds
function stopColors() {
    clearInterval(x);
}

//Activate printing by selecting an option.
function generateColors(interval){
    document.getElementById("options").onclick = Colors(interval);
    /*same result with onchange
     I even sent the JSFiddle settings per this link:
      http://bit.ly/1gev7zR*/
}

generateColors('second');

【问题讨论】:

标签: javascript function onclick onchange


【解决方案1】:

你不能像这样附加一个事件监听器,它会立即调用 Colors 函数。

您可以将其包装在一个函数中,也可以使用 addEventListener,

function generateColors(interval){
    document.getElementById("options").onclick = function() {
        Colors(interval);
    }
}

第二种方法,

function generateColors(interval) {
    var el = document.getElementById("options");
    el.addEventListener("click", function () {
        Colors(interval);
    });
}

Updated DEMO

【讨论】:

  • 仍然很困惑为什么它会立即触发;我正在使用 onclick 不点击方法。无论如何,使用 Jealie 发布的链接中提到的 jQuery 方法作为答案: $("target").change(function(){myfunction();});对 JS 来说还是新手,但 jQuery 答案与您的原生答案本质上不一样——为现有的事件侦听器更改创建一个匿名函数吗?我猜想 jQuery 省去了编写所有这些本机代码的工作。不过感谢这个答案! =)
  • @brooklynsweb: element.onclick 需要一个函数处理程序,而不是函数值。因此,element.onclick = myfunction; 按预期工作,并且在设置时不会触发对 myfunction() 的调用,但element.onclick = myfunction(); 在设置 element.onclick 时会评估 myfunction 返回的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 2015-08-15
  • 2016-06-18
相关资源
最近更新 更多