在chrome中查找具有未定义值的元素

Find elements that have non defined value in chrome

本文关键字:未定义 元素 chrome 查找      更新时间:2023-09-26

我需要在jquery中选择元素值=="的查询。我在IE工作,但不是在chrome。我认为铬有另一个价值作为非定义的价值。

我查询:

var images = $('#images>div>input[type=file][value=""]');
if(images.length > 0) // ...

正如你所看到的,有一个文件类型的输入元素,它给用户一个附加图像的机会。

<div id="files">
<div><input type="file" name="files" /><input type="button" value="Remove" onclick="removeImage(this)" /></div>
<div><input type="file" name="files" /><input type="button" value="Remove" onclick="removeImage(this)" /></div>
<div><input type="file" name="files" /><input type="button" value="Remove" onclick="removeImage(this)" /></div>
</div>

在IE中它工作得很好,但在chrome中它总是返回0个元素。

你有什么可以在所有浏览器上工作的解决方案吗?

这行得通:

$('#show').click(function(){
    $(':input[type="file"]').each(function(){
        if($(this).val() == this.defaultValue)
        {
            $(this).css('border','2px solid red');
        }
    });
});

与其尝试将内容与变量空字符串或'fakepath'等进行比较,不如将其与自己的defaultValue进行比较,您将知道它是否已填充。

http://jsfiddle.net/AlienWebguy/5sK7T/

试试这个…

var images = $('#images > div > :file')
              .filter(function() { return $(this).val().length; });

Chrome, Firefox &IE绝对可以得到value(虽然Chrome只会告诉你文件名加上C:'fakepath')。

你的浏览器显示什么?

我合并了你的两个答案,最后我写了这个:

var images = $(':input[type="file"]').filter(function() { 
    return $(this).val()==this.defaultValue; 
});

这个效果很好。谢谢。