$(“#id”).val() : No find
$(“input[id=‘id’]”).val() : OK
你知道上述两种情况之间的区别吗?为什么要这么做?
你问为什么:
$(“#id”).val() // <--- This doesn't work,
// and
$(“input[id=‘id’]”).val() // <--- ... and this does work?
假设您的标记看起来像这样:
<label for="id"> Input </label> <br />
<input id="id" type="text" value="test"/>
...如果是这种情况,那么以下内容应该可行(我已经包含了vanilla JS Comparisons以供参考,这与jQuery如何在引擎盖下工作非常接近)。
// The jQuery Way
const firstCase = $("#id").val() // "test"
const secondCase = $("input[id='id']").val() // "test"
// The Vanilla Way
const thirdCase = document.getElementById("id").value; // "test"
const fourthCase = document.querySelector("input[id='id']").value; // "test"
请提供您尝试与之交互的HTML标记,然后我们将更好地了解您要解决的问题。
要回答这个问题,我们需要了解Jquery选择器的工作原理。
$("#id")
内部使用document.getElementById();
$("input[id='id']")
在内部使用document.getElementsByTagName()
来获取所有匹配的“元素标记”和带有id的过滤器。
两个操作之间的主要区别是案例1仅返回匹配对象,但案例2与prevObj或包含对象一起返回。
因此,从技术上讲,使用val()
的两个操作都应返回相同的结果。