简体   繁体   English

jQuery中的选择器^-怎么做?

[英]selector ^ in jQuery - how to all?

<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'>");
});

why this working only for first input? 为什么这只对第一次输入有效? if first input value is null then this add css for all input. 如果第一个输入值为null,则为所有输入添加CSS。 how can i make it separately for all input? 我如何才能对所有输入分别进行设置? i use also function live() - i would like added this also for new input 我也使用live()函数-我也想为新输入添加它

LIVE EXAMPLE: http://jsfiddle.net/Zm5jp/1/ 实时示例: http //jsfiddle.net/Zm5jp/1/

val gets the value of the first element in the matched set . val获取匹配集中第一个元素的值。 You'll have to iterate over the set : 您必须遍历集合

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

You need to iterate over the inputs matched using each ; 您需要遍历使用each匹配的inputs

$('input[id^="aaa"]').each(function () {
    var self = $(this);

    if (self.val().length == 0) {
        self.css('background-color', 'red');
    }
}

As stated in the docs for val() ; 文档中对val()

Get the current value of the first element in the set of matched elements. 获取匹配元素集中第一个元素的当前值。

Ie your code translates as "if the first input value is empty, set the background CSS for all elements" 即您的代码翻译为“如果第一个输入值为空,则为所有元素设置背景CSS”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM