jQuery 查找不适用于属性选择器

jQuery find not working with attributes selectors?

本文关键字:属性 选择器 适用于 不适用 查找 jQuery      更新时间:2023-09-26

>我有一个页面,其中包含一个表单:

  • $('form').find('input[type=submit]')[undefined]
  • 但是$('form input[type=submit]')按预期工作...

正常吗?

两者都可以正常工作

console.log($('form').find('input[type=submit]').val());
console.log($('form input[type=submit]').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="submit" value="somevalue" />
</form>

你应该显示更多的代码,但如果你得到undefined你可能没有真正加载jQuery库。

如果您使用的是 Windows 桌面,则您的浏览器可能具有开发人员工具(通常为 F12(,您可以使用它们来查看 JavaScript 控制台并在执行代码时调试(单步执行(代码。

jQuery 选择器的返回值是一个数组,通常要验证您是否选择了单个元素,您只需检查该数组的长度(假设 jQuery 已正确加载,您可以通过在控制台中键入 jQuery 来测试它,控制台应该显示function(a,b){...}或类似,而不是抛出有关未定义引用的异常(。

若要测试这些示例,请先打开 JavaScript/开发工具控制台,然后单击"运行代码段">

工作代码(jQuery已加载(

var $elem = $("form input[type='submit']");
if ($elem.length === 1) {
    if (console) console.log("found the element");
} else {
    if (console) console.log("did not find the element (could inject it, or log error, etc.)");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input type='submit' value='Submit form' />
</form>

非工作代码(未加载jQuery(

try
{
var $elem = $("form input[type='submit']");
if ($elem.length === 1) {
    if (console) console.log("found the element");
} else {
    if (console) console.log("did not find the element (could inject it, or log error, etc.)");
}
}
catch (ex)
{
if(console)console.log(ex.message);
}
<form>
    <input type='submit' value='Submit form' />
</form>