【问题标题】:Getting a submit selection into a variable with jQuery使用 jQuery 将提交选择放入变量中
【发布时间】:2015-05-21 10:39:19
【问题描述】:

我正在做一个验证某个类的条件,并且根据值,可敬的提交输入存储到一个变量中:

_btnAjax = "";

if (_aVar.hasClass("one")) {
    _btnAjax = $("#one");
}
if (_aVar.hasClass("two")) {
    _btnAjax = $("#two");
}

然后,在该变量上使用.on('click' function(e){});

_btnAjax.on('click', function(e) {
     // some Ajax
}

问题是我收到错误TypeError: _btnAjax.on is not a function

我已经在<li></li> 上做了完全相同的事情,但是<button></button><input type='submit'/> 都不起作用。

【问题讨论】:

    标签: javascript jquery jquery-selectors jquery-events


    【解决方案1】:

    失败的原因是你的两个条件都不成立。

    例如,如果_aVar 没有one 类并且它没有two 类,那么_btnAjax 是您代码中的字符串。

    仔细检查您的 UI 是否具有正确的类。

    此外,请务必处理其他情况。

    试着像这样写你的代码:

    var _btnAjax;
    
    if (_aVar.hasClass("one")) {
        _btnAjax = $("#one");
    } else if (_aVar.hasClass("two")) {
        _btnAjax = $("#two");
    } else {
        // Do something to handle the fact that neither case was true.
        //  You can return early, throw an error, or set _btnAjax to
        //  an empty jQuery object.
    }
    

    【讨论】:

      【解决方案2】:

      您正在尝试使用 jQuery 函数 (.on) 试试这个:

      $(_btnAjax).on('click', function(e) {
          // some ajax
      }
      

      虽然我认为您应该使用 id 或类选择器,例如:

      // selector should be whatever your button has as id or class property.
      // (preferably an id since this won't conflict with other classes)
      $('#btnAjax').on('click', function(e) {
          // some ajax
      }
      

      【讨论】:

      • 我这样做是因为我有两个表格,我不想重复代码。第一个建议有效,它没有显示错误,但也没有使 Ajax 工作,如果我只是提出第二个建议,它就可以工作。
      • 好的,那么您的问题解决了吗?
      猜你喜欢
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      相关资源
      最近更新 更多