是否可以将多个HTML元素合并到jQuery中的一个脚本中?

时间:2019-12-22 04:04:19

标签: javascript jquery html

我在HTML中使用了多个元素,脚本是相同的。那么有可能将多个HTML元素合并到jQuery中的一个脚本中吗?代码越短越容易管理。

要成为:

$("#edit_rules_form input select textarea").each(function(){
    if(!$(this).val()){
        $(this).tooltip("show");
        checkfieldvalue = false;
        $(this).on("focus", function(){
            $(this).tooltip("hide");
        });
    }
});

当前的jQuery:

$("#edit_rules_form input").each(function(){
    if(!$(this).val()){
        $(this).tooltip("show");
        checkfieldvalue = false;
        $(this).on("focus", function(){
            $(this).tooltip("hide");
        });
    }
});

// Tooltip for <select> dropdown
$("#edit_rules_form select").each(function(){
    if(!$(this).val()){
        $(this).tooltip("show");
        checkfieldvalue = false;
        $(this).on("focus", function(){
            $(this).tooltip("hide");
        });
    }
});

// Tooltip for <textarea> box
$("#edit_rules_form textarea").each(function(){
    if(!$(this).val()){
        $(this).tooltip("show");
        checkfieldvalue = false;
        $(this).on("focus", function(){
            $(this).tooltip("hide");
        });
    }
});

1 个答案:

答案 0 :(得分:2)

您可以使用comma-https://api.jquery.com/multiple-selector/编写多个选择器。

$("#edit_rules_form input, #edit_rules_form select, #edit_rules_form textarea").each(function(){
    if(!$(this).val()){
        $(this).tooltip("show");
        checkfieldvalue = false;
        $(this).on("focus", function(){
            $(this).tooltip("hide");
        });
    }
});