选择器^在jQuery -如何所有

selector ^ in jQuery - how to all?

本文关键字:何所 jQuery 选择器      更新时间:2023-09-26
<input id="aaa1" value="vvv">
<input id="aaa2" value="">
<input id="aaa3" value="ooo">
<input id="aaa4" value="">
<input id="aaa5" value="ooo">
<input id="aaa6" value="ooo">
if($('input[id^="aaa"]').val().length == 0){
    $('input[id^="aaa"]').css('background-color', 'red');
}
$("#aaa1").live("click", function(){
  $(this).after("<input id='aaax' value='ooo'>");
});

为什么这只适用于第一次输入?如果第一个输入值为null,则为所有输入添加CSS。我怎样才能对所有的输入分别设置呢?我还使用了live()函数-我还想为新输入

添加此函数

生活例子: http://jsfiddle.net/Zm5jp/1/

您需要遍历使用each匹配的inputs;

$('input[id^="aaa"]').each(function () {
    var self = $(this);
    if (self.val().length == 0) {
        self.css('background-color', 'red');
    }
}

val()的文档中所述;

获取匹配元素集合中第一个元素的当前值。

。你的代码翻译成"如果第一个输入值为空,设置所有元素的背景CSS "

val获取匹配集合中第一个元素的值。你必须遍历集合:

$('input[id^="aaa"]').each(function() {
    if($(this).val().length == 0) {
        $(this).css('background-color', 'red');
    }
});