【问题标题】:onchange() in JavaScript or JqueryJavaScript 或 Jquery 中的 onchange()
【发布时间】:2014-07-18 10:27:25
【问题描述】:

早安,

我有一个 drop down list,其中有一个 onchange 函数调用 updateView()jsp代码如下:

<s:select name="accountDateRange" onchange="updateView();" id="function" >

但是,使用这个功能的不只是这个drop down list。其他一些函数可能会调用updateView() 来继续。

当用户在此drop down list 上执行onchange 时,我需要运行一些代码,但我不希望在其他函数调用updateView() 时运行此代码。

以下是updateView()的部分代码:

function updateView() {

    // some other code here

        // here is the code that I only want to run during onchange
        $("#fromDate").val("");

    // some other code here

}

我尝试在下拉列表中放入一个onclick 函数,在这个onclick 函数中,我将一个变量设置为true。

这样我就可以在运行$("#fromDate").val("");之前使用这个变量进行检查,比如:

if (onchangeOnly = true){
  $("#fromDate").val("");
}

但是,我发现onchange 将首先运行与onclick 比较。

有什么办法或想法吗?请多多指教。

编辑:

function updateView() {

    // some other code here
    if ($("#function").val() == "TODAY") {
        // some other code here..
    }
    else if ($("#function").val() == "DATERANGE") {
        // here is the code that I only want to run during onchange
        $('[name="accountDateRange"]').on('change',function(){
                    alert('this is specific to this dropdown only');
                });
     } 
    // some other code here

}

我发现,即使我的$("#function").val()不等于“DATERANGE”,它也会打印出alert('this is specific to this dropdown only')。请指出我的错误。

【问题讨论】:

  • 为什么不给你的函数updateView添加一个参数,就像updateView(para)一样。将true 发送到您希望发生此更改的地方,其他人请勿发送
  • 嗨,这是一种解决方法。但是我有很多功能是使用这个updateView,如果我添加一个参数,我需要做很多修改。因此,我不想这样做。
  • 不,你不需要,只是不要从另一端发送
  • 既然您已经在使用jQuery,那么为什么要附加这样的处理程序onchange="updateView();",如果您可以像下面的答案(@LIUFA)中发布的那样做呢?这样您就可以确切地知道是哪个元素触发了该事件。
  • 其他人将是undefined

标签: javascript jquery onclick onchange


【解决方案1】:

您可以为同一个事件添加多个处理程序,这意味着您可以离开现有函数并编写一个新函数,然后将此函数添加到下拉列表中,这样其他触发updateView()的机制将不受影响。

$('[name="accountDateRange"]').on('change',function(){
alert('this is specific to this dropdown only');
})

【讨论】:

  • @LIUFA,对我的问题进行编辑。请再次提供帮助。
  • $('[name="accountDateRange"]').on('change',function(){ alert('this is specific to this dropdown only'); }) 进入单独的页面&lt;script&gt;&lt;/script&gt;,而不是进入函数updateView()
【解决方案2】:

我会在 jQuery 中做到这一点,而不添加 onchange 到选择元素

js

$(document).ready(function(){
  $('#mySelect').bind('change', function(e){
    updateView(e.currentTarget.id)
  })
})

updateView = function (selectId) {
  if(selectId !== 'mySelect'){
    return;
  }
  alert('called from mySelect')
}

工作的笨蛋 http://plnkr.co/edit/EmSowz6osgse2Ou8g6FC?p=preview

【讨论】:

  • 你的想法更好。 +1
  • 谢谢,我也这么认为;)
【解决方案3】:

onclick 不适用于仅在 onchange 函数中的下拉列表,您需要使用您的函数。并决定使用这样的参数:

function updateView(bool) {
   if(bool){
    //do your stuff
   }
}

另一种方法是在新的 onchange 中添加新函数,如 LIUFA 所述,但请确保使用 stopPropagation 或返回 false 以使其工作。

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多