如果我在一个元素中有一个文本字符串,如果该文本与给定的字符串匹配,那么 jQuery 中最有效的返回方式是什么。
例如,
<div id="myDiv">This is a test</div>
$("#myDiv").eq("This is as test"); // returns true or false
但是 eq 不是正确的功能
如果我在一个元素中有一个文本字符串,如果该文本与给定的字符串匹配,那么 jQuery 中最有效的返回方式是什么。
例如,
<div id="myDiv">This is a test</div>
$("#myDiv").eq("This is as test"); // returns true or false
但是 eq 不是正确的功能
jQuery:
$('#myDiv').text() === "This is as test";
请注意,如果 DOM 包含其他节点或奇怪的间距等,这会变得很难看。但是对于您控制的简单节点,这是最简单的方法。
我自己会使用grammar31解决方案,但只是为了好玩,这里有一些其他方法:
$("#myDiv:contains('This is a test')").length==1;
document.getElementById('myDiv').innerHTML == 'This is a test';
if($("#myDiv").text() === 'This is a test'){ /* true */ }else{ /* false /* }