我有代码: 搜索单个字符串并返回整个字符串。
$(document).ready(function() {
$('button').click(function (){
var search = $('#input').val();
var str = $('#file').html();
var output=str.match(search );
document.getElementById("result").innerHTML = output;
if (search.value.length > 0) {
$(".oh").show().filter(function () {
return $('#input').find('li').text().toLowerCase().indexOf($("search").val().toLowerCase()) == -1;
}).hide();
}
else {
$(".oh").show();
document.getElementById( 'oh' ).style.display = 'block';
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="searchbox.js"></script>
</head>
<body>
<input type="text" id="input">
<button>solve</button>
<p id="result"></p>
<div id="file"class="oh"style="display:none;">
<li>beatiful</li>
<li>happy sunday</li><li>good morning</li><li>good evening</li><li>oh my god</li>I like u</li><li>wonderful day</li>
<li>good aftnoon</li>
</div>
</body>
</html>
例如:
`input = good
output = good morning,
good night,
good noon`
`input = morning,
output = good morning`
它就像html中的搜索框一样 请帮助我任何建议或更正我的代码它对我更有帮助我使用jquery和index()正在使用但它不起作用
答案 0 :(得分:0)
检查一下,我已经稍微更新了你的标记,并将代码改为工作:
$(document).ready(function() {
$('button').click(function() {
var search = $('#input').val(); // get the search term
var $lis = $('#file li'); // all the existing li items to filter/search
var $resUl = $('#result ul'); // the ul to show results
var o = $lis.map(function() { // map will let you loop through list items
if (this.textContent.indexOf(search) != -1) { // check if the current li in the iteration has the search term
return $(this).clone(); // if yes then return a copy of it.
}
}).get(); // .get() will create an array when used with .map()
$resUl.empty(); // always clear the result ul
$.each(o, function(i, item) { // loop through the array created via filter
$resUl.append(item).find('li').fadeIn(); // here append them as lis are hidden so fade them in the view to show.
});
});
});
#file li {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<input type="text" id="input">
<button>solve</button>
<div id="result">
<ul></ul>
</div>
<ul id="file">
<li>beatiful</li>
<li>happy sunday</li>
<li>good morning</li>
<li>good evening</li>
<li>oh my god</li>
<li>I like u</li>
<li>wonderful day</li>
<li>good aftnoon</li>
</ul>
答案 1 :(得分:0)
$(document).ready(function() {
$('button').click(function (){
var searchval = $('#input').val();
var str = $('#file').html();
var rep2 = str.split('</li>');
var rep3 = rep2.filter(function(item){
if(item.search(searchval) !=-1){
return item;
}
})
document.getElementById("result").innerHTML = rep3;
});
});