[英]shorter way to check if a title exists
Checking if a title
already exists. 检查title
已经存在。 Is there a shorter way? 有没有更短的方法? Something like: 就像是:
if(test.exists.inside('.title'){...
var x = 0; var test = $('#test').text(); $('.title').each(function(){ if($(this).text() == test){x = 1;} }); if(x == 1){console.log('exists');}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>lorem</div> <div class='title'>ipsum</div> <div class='title'>lorema</div> <div class='title'>ipsuma</div> <div id='test'>lorem</div>
a lot of ways to do this :contains
, filter()
with indexOf()
and filter()
with text
equal test
.. depending on what you're trying to do 有很多方法可以做到这:contains
, filter()
用indexOf()
和filter()
与text
同等test
..这取决于你想做什么
var x = 0; var test = $('#test').text(); var Exists = $('.title:contains("'+test+'")').length; console.log('Yes '+Exists+ ' title with text '+test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>lorem</div> <div class='title'>ipsum</div> <div class='title'>lorema</div> <div class='title'>ipsuma</div> <div id='test'>lorem</div>
you can check also with for contains text check 您也可以检查是否包含文本检查
$('.title:contains("'+test+'")').length > 0
OR for exact text check 或 进行精确文本检查
$('.title').filter(function(){
return $(this).text().trim() == test;
}).length > 0
Note:
:contains
and.indexOf
search for the text contains text not the exact text .. by using$(this).text().trim() == test;
注意:::contains
和.indexOf
搜索文本包含的文本不是确切的文本..通过使用$(this).text().trim() == test;
this will return the exact text element 这将返回确切的文本元素
If you're just looking for shorter code, one option would be to invoke Array.prototype.some
, and rather than store the result of .text()
in a variable, invoke it every time, to save on characters typed: 如果您只是在寻找较短的代码,一种选择是调用Array.prototype.some
,而不是将.text()
的结果存储在变量中,而是每次都调用它,以节省键入的字符:
if ([].some.call($('.title'), d => $(d).text() === $('#test').text())) { console.log('exists'); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>lorem</div> <div class='title'>ipsum</div> <div class='title'>lorema</div> <div class='title'>ipsuma</div> <div id='test'>lorem</div>
Personally, I'd prefer readability over code length: 就个人而言,我宁愿可读性胜于代码长度:
const textToFind = $('#test').text(); const exists = Array.prototype.some.call( $('.title'), title => $(title).text() === textToFind ); if (exists) { console.log('exists'); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='title'>lorem</div> <div class='title'>ipsum</div> <div class='title'>lorema</div> <div class='title'>ipsuma</div> <div id='test'>lorem</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.