One*_*red 5 html javascript jquery
我是html/javascript的新手,当用户在文本框中输入值时,我试图将焦点放在html元素内的文本/单词上.
<input type="text" id="search">
<input type="button" id="button" onsubmit="searchKey" value="Find">
<div>
<p>some text here</p>
</div>
Run Code Online (Sandbox Code Playgroud)
因此,如果用户在输入框中输入"text",它应与文本匹配并关注它
使用jQuery,这个 jsFiddle显示了段落中找到的文本的基本突出显示。我提到basic是因为它会删除段落内的所有 html 标签,只考虑内部的原始文本。
编辑:脚本现在保留其他标签和样式,但不完全。当尝试查找会与另一个标签(例如<span class="matched-text">(te<strong>xt)</span>.</strong>)产生冲突的文本时,该文本将不起作用,因此该实例被取消。
$('#button').click(function() { // Trigger when button is clicked
var searchText = $('#search').val(); // Store text of input field
var foundParagraph = $('p:contains(' + searchText + ')'); // Get the paragraph(s) that contain the search string
var customStylingClass = '.matched-text';
$(customStylingClass).each(function() {
var text = $(this).text(); //get span content
$(this).replaceWith(text); //replace all span with just content
});
foundParagraph.each(function() {
$(this).html(($(this).html().replace(searchText, '<span class="matched-text">$&</span>'))); // Highlight with strong text
})
});Run Code Online (Sandbox Code Playgroud)
.matched-text {
background-color: yellow;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="search">
<input type="button" id="button" value="Find">
<div>
<p>some text here</p>
<p>Lorem ipsum dolor sit amet (te<b>xt)</b>.</p>
<p>Styling will <strong>not</strong> be removed <i>anymore</i></p>
<p>
Not any <span class="tag">tag</span> at all.
If there is a conflict with tag closings, the operation will just cancel for the instance.
</p>
</div>Run Code Online (Sandbox Code Playgroud)