【问题标题】:How to combine jQuery-functions with different selectors如何将 jQuery 函数与不同的选择器结合起来
【发布时间】:2015-10-11 12:08:17
【问题描述】:

我有未知数量的不同 ID,例如 #send_1#send_2 等等。我需要为每个 ID 调用一个 jQuery,例如:

$(document).on("submit", "#send_1", function(e){
    var i=1;
    if (something is true) {
        do something
    }    
});
$(document).on("submit", "#send_2", function(e){
    var i=1;
    if (something is true) ) {
        do something
    }    
});

所以我可以写一百次相同的函数,只是改变_x,但应该有更合适的方法来解决这个问题。

我通常不使用 jQuery,所以如果有人可以帮助我,我真的很感激。

提前致谢。

【问题讨论】:

  • 我的回答有错字。立即尝试

标签: jquery ajax jquery-selectors


【解决方案1】:

使用属性starts with(^=) 选择器

$(document).on("submit", '[id^="send_"]', function(e){
    var i=1;
    if (something is true) ) {
        do something
    }    
});

【讨论】:

  • @John,很高兴它有帮助:)
【解决方案2】:

你也可以用','分隔它们

像这样:

$(document).on("submit", "#send_1, #send_2", function(e){
//...
});

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多