如何通过最匹配的文本获取元素?
How can I get an element by it's closest matching text?
我有多个 h3
,其中包含各种文本。我想 select 一个元素的文本内容。但我没有从后端收到准确的文本匹配。
但我有部分可加工的文本。使用这个我怎么能select受人尊敬的元素。
示例html:
<h3>civil</h3>
<h3>mechanical</h3>
<h3>electrical</h3>
js :
var text = "civil engineering";
var element = $('h3').closest(":contains('"+text+"')");
console.log(element);
这里我有 var text = civil engineering
使用这个我想 select h3
元素。
搭配不止这个,还有很多。我想匹配文本 closest
.
您可以使用indexOf()
函数:
var h3 = $('h3');
var str = 'civil engineering';
h3.each(function() {
if (str.toLowerCase().indexOf($(this).text()) >= 0) {
$(this).addClass('found');
}
});
每个 h3
包含您设置的字符串,得到 class .found
我理解正确
您需要使用.filter()
in combination with indexOf()
var text = "civil engineering";
var element = $('h3').filter(function(){
return text.indexOf($(this).text()) != -1;
});
$(document).ready(function() {
var text = "civil engineering";
var element = $('h3').filter(function() {
return text.indexOf($(this).text()) != -1;
});
console.log(element.text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>civil</h3>
<h3>mechanical</h3>
<h3>electrical</h3>
我有多个 h3
,其中包含各种文本。我想 select 一个元素的文本内容。但我没有从后端收到准确的文本匹配。
但我有部分可加工的文本。使用这个我怎么能select受人尊敬的元素。
示例html:
<h3>civil</h3>
<h3>mechanical</h3>
<h3>electrical</h3>
js :
var text = "civil engineering";
var element = $('h3').closest(":contains('"+text+"')");
console.log(element);
这里我有 var text = civil engineering
使用这个我想 select h3
元素。
搭配不止这个,还有很多。我想匹配文本 closest
.
您可以使用indexOf()
函数:
var h3 = $('h3');
var str = 'civil engineering';
h3.each(function() {
if (str.toLowerCase().indexOf($(this).text()) >= 0) {
$(this).addClass('found');
}
});
每个 h3
包含您设置的字符串,得到 class .found
我理解正确
您需要使用.filter()
in combination with indexOf()
var text = "civil engineering";
var element = $('h3').filter(function(){
return text.indexOf($(this).text()) != -1;
});
$(document).ready(function() {
var text = "civil engineering";
var element = $('h3').filter(function() {
return text.indexOf($(this).text()) != -1;
});
console.log(element.text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>civil</h3>
<h3>mechanical</h3>
<h3>electrical</h3>