我试图清除输入字段中包含某个值的值。
$('#registerajax_email:contains("yahoo.com")').text(function(){
$('#registerajax_email').val('');
});
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我认为问题在于输入字段的值包含在value属性中,而不包含在元素的内容中。您需要一个属性选择器。
尝试这个:
$('#registerajax_email[value*="yahoo.com"]').val('');
Run Code Online (Sandbox Code Playgroud)
使用属性包含选择器
这是与值匹配的最慷慨的jQuery属性选择器。如果选择器的字符串出现在元素属性值内的任何位置,它将选择一个元素。
您使用的选择器(:contains()选择器)不会查看元素属性:
匹配的文本可以直接出现在所选元素中,该元素的任何后代或其组合中。
但是,由于要按ID定位元素,因此您实际上根本不需要使用属性选择器。正如罗伯特·科里特尼克(Robert Koritnik)建议的那样,此代码很可能应该包含在一个事件中,您可以使用简单的indexOf来检查字符串是否包含:
// Register event onBlur (you could also use change, or whatever event suited the situation)
$('#registerajax_email').blur(function() {
// Does value contain yahoo.com?
if ($(this).val().indexOf("yahoo.com") != -1)
{
// clear the value
$(this).val("");
}
});
Run Code Online (Sandbox Code Playgroud)