属性从选择器开始[name ^ = value]

时间:2010-08-16 10:23:58

标签: javascript jquery

我需要按名称匹配一些输入字段。名称由基本名称和方括号组成,因此PHP解释器将它们转换为数组。根据jQuery API,我可以使用以下选择器:

":input[name^=foo\\[]"

(可以忽略右括号。)但是,它不会匹配任何元素。其他变化会触发我无法正常捕获的异常。我错过了什么?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
    // Expected result: 4
    var found = [];

    // 5
    found.push($(":input[name^=foo]").size());

    // uncaught exception: Syntax error, unrecognized expression: ]
    //found.push($(":input[name^=foo[]").size());

    // undefined
    try{
        found.push($(":input[name^=foo[]").size());
    }catch(e){
        found.push("Exception: " + e.description);
    }

    // uncaught exception: Syntax error, unrecognized expression: ]
    //found.push($(":input[name^=foo\[]").size());

    // undefined
    try{
        found.push($(":input[name^=foo\[]").size());
    }catch(e){
        found.push("Exception: " + e.description);
    }

    // 0
    found.push($(":input[name^=foo\\[]").size());

    alert("Items found:\n" + found.join("\n"));
});
//--></script>
</head>
<body>

<p><input type="text" name="foo[-1]" value="A"></p>
<p><input type="text" name="foo[0]" value="B"></p>
<p><input type="text" name="foo[1]" value="D"></p>
<p><input type="text" name="foo[]" value="D"></p>
<p><input type="text" name="foobar" value="Z"></p>


</body>
</html>

1 个答案:

答案 0 :(得分:4)

尝试引用该值:

":input[name^='foo[']"