这是场景 我有这个观点 这是我的Javascript代码与jQuery混合在一起 这是我的网络应用程序的屏幕截图(我正在使用laravel 5.4) 当我单击“填充数量/包”和“数量”字段中的数据时,“包”字段也应相应更新,例如 如果数量/包是5,并且我要赠送 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我正在尝试使用jQuery构建“简单”突出显示功能。 由于某种原因,这使我的HTML重复了,我不确定为什么。 我要做的就是在搜索栏中键入搜索文本,并在键入时突出显示标签中的文本。
有什么想法吗? 绝望...
这是HTML和JS
function hiLite(searchWords) { if (searchWords) { var content = $("p").text(); var regExp = new RegExp(searchWords, "ig"); var matches = content.match(regExp); if (matches) { $("p").html(content.replace(regExp, function(match) { return "<span class='highlight'>" + match + "</span>"; })); } else { $(".highlight").removeClass("highlight"); } } else { $(".highlight").removeClass("highlight"); } }; $("#searchBar").keyup(function() { var userInput = $(this).val().toLowerCase(); hiLite(userInput); });
<!doctype html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="photo_filter.css" type="text/css"> </head> <body> <div class="search">Search: <input type="text" id="searchBar"> </div> <div id="results"> <p>some text is here</p> <p>other kinds</p> <p>even more</p> </div> </body> </html>
最大的问题是,当您确实需要分别评估每个<p>
标签时,您一次选择了所有<p>
标签。
如果我有3个<p>
标记,并且这样做: $('p').html('I am ap tag!!');
-然后每个<p>
标签都会受到影响。
同样,如果我这样做: var content = $('p').text();
-然后, content
等于"some text is hereother kindseven more"
,即每个 <p>
标记中的文本。 这不好!
尝试这个:
function hiLite(searchWords) {
if (searchWords) {
$('p').each(function(index, single_p) {
var text = $(single_p).text(); // .text() does not include html, does not include any former <spans>
$(single_p).html(text); // reset <p> html to be only the text from previous line
var regExp = new RegExp(searchWords, "ig");
var new_text = text.replace(regExp, '<span class="highlight">' + searchWords + '</span>'); // create new text with HTML highlight
$(single_p).html(new_text); // update DOM with our new HTML
});
}
};
$("#searchBar").keyup(function() {
var userInput = $(this).val().toLowerCase();
hiLite(userInput);
});
解决方案2:
添加了条件以根据搜索文本突出显示文本
JS代码:
function hiLite(searchWords){
if(searchWords){
var content = $("p").text();
var regExp = new RegExp(searchWords, "ig");
var matches = content.match(regExp);
if(matches){
$('#results p').each(function() {
var test = '<span class="highlight">'+searchWords+'</span>';
var text = $(this).text();
$(this).html(text.replace(regExp, test));
});
}
}
};
$("#searchBar").keyup(function(){
var userInput = $(this).val().toLowerCase();
hiLite(userInput);
});
HTML代码:
<div class="search">Search:
<input type="text" id="searchBar">
</div>
<div id="results">
<p>some text is here</p>
<p>other kinds</p>
<p>even more</p>
</div>
CSS:
.highlight{
color:red
}
JSFiddle :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.