JavaScript或Jquery中的onchange()

时间:2014-07-18 10:27:25

标签: javascript jquery onclick onchange

美好的一天,

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

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

但是,不仅此drop down list使用此功能。其他一些功能可能会调用updateView()继续。

当用户在onchange上执行drop down list时,我需要运行一些代码,但我不希望在其他函数调用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')。请指出我的错误是什么。

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

我只是在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

答案 2 :(得分:0)

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

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

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