使用jQuery将提交选择转换为变量

时间:2015-03-18 15:05:04

标签: javascript jquery javascript-events jquery-selectors

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

_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'/>都不起作用。

2 个答案:

答案 0 :(得分:1)

失败的原因是因为你的两个条件都不正确。

例如,如果_aVar没有one类且它没有two类,那么_btnAjax就是代码中的字符串。< / p>

仔细检查您的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.
}

答案 1 :(得分:0)

您正在尝试使用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
}