首页 > 解决方案 > jQuery 选择器 $("input[with="+id+"]")

问题描述

这个 jQuery 选择器实际上是如何工作的?

$("input[with="+id+"]")

在这个函数内部使用:

function enableFields(id) {
    $("input[with="+id+"]").each(function() {
        $(this).attr('disabled', false);
    });   
}

说“选择所有input具有with属性的元素。在当前input元素上,将with属性值设置为当前元素的id属性值”是否正确?

本质上,如果输入元素看起来像<input id="idValue" with="withValue">,则暂时将with属性设置为id从中查找的值<input id="idValue" with="idValue">并使用它来选择要调用的元素each()

标签: javascriptjquery

解决方案


仅在针对多个输入进行更新时才使用每个。使用 id 与类名让我认为你的意图是一次进行单个输入更新。不再使用 disabled false ,因为大多数现代浏览器将 disabled 的存在解释为“已禁用”。如果要更新多个输入,请使用 className 选择器而不是 id。

保持独特身份的精神:

function enableFields(id) {
    $("#" + id).removeAttr('disabled');
}

使用类名更新多个输入:

function enableFields(className) {
    $("." + className).each(function() {
        $(this).removeAttr('disabled');
    });   
}

推荐阅读