我正在尝试通过id为“Holder”的div来查找并搜索字符串。优选地,该字符串不区分大小写。该字符串将连接一个输入(变量是'Terms')。一旦代码找到了包含字符串的所有段落,就为它们添加一个名为“Found”的类。我对Jquery没有那么多的知识(只是非常基础),所以如果有人能帮助我,那就太棒了!
到目前为止代码:
<!DOCTYPE html>
</html>
<body>
<p id="header">Searcher</p>
<hr>
<p id="form">
<input autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase">
<button type="button" id="sea" onClick="Search ()">Search</button>
<br>
</p>
<div id="Holder">
<p id="Note">This is a test paragraph uses to test.</p>
<p id="Note">For jquery. I want to search for this paragraph using "for jquery".</p>
</div>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="test.js">
</script>
</body>
答案 0 :(得分:0)
这是一个工作代码示例。您应该阅读评论,因为我对您的工作方式进行了一些更改,以提高代码质量。还有更多可以做的事情(比如使用真实形式),但这应该让你指向正确的方向。如果我的评论不清楚,请随时问我为什么做了我所做的更改,并且我会尝试提供更好的解释。
<html>
<style>
.match-found {
background: yellow;
}
</style>
<body>
<p id="header">Searcher</p>
<hr>
<p id="form">
<!--
You should use a real form and attach to the submit handler, but I
feel the need to leave something as an exercise for the reader
-->
<input autocomplete="off" id="bar" name="input" type="text" placeholder="Search for word or phrase">
<button type="button" class="search-text" data-search-target="#holder">Search</button>
<br>
</p>
<div id="holder">
<p id="note">This is a test paragraph uses to test.</p>
<p id="note">For jquery. I want to search for this paragraph using "for jquery".</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function search(searchTarget, term) {
// lowercase terms because uppercase should be reserved for constructors
// also made it singular because we're looking for an exact match, not
// a list several separate terms.
// (if I understand your problem description correctly)
term = term.toLowerCase();
// If you're searching for simple terms, regex would be better,
// but since I'm not sure how you'll actually be using this,
// lowercasing the string and searching for a containing string will
// provide more consistent results because we won't have to worry about
// escaping special characters and the like.
$(searchTarget).find('p').each(function() {
var searchText = $(this).text().toLowerCase();
if (searchText.indexOf(term) !== -1) $(this).addClass('match-found');
// match-found is more descriptive that 'found'.
// Also avoiding caps again because capitilization has specific meaning
});
}
// A better way to attach event listeners
$(document).ready(function() {
$('.search-text').click(function() {
var searchTarget = $(this).attr('data-search-target');
var searchText = $('#bar').val();
search(searchTarget, searchText);
});
});
</script>
</body>
</html>
答案 1 :(得分:0)
$("#sea").on("click", function() {
$("#Holder > p:contains('" + $("#Bar").val() + "')").addClass("found");
});
上面的代码将点击事件附加到搜索按钮#sea
。使用:contains()
选择器,它会搜索所有<p>
个#Holder
直接子项的标记,其值为#Bar
,并添加“找到”类。