我想用普通的javascript搜索<p>
,但我无法弄清楚如何。我试过谷歌搜索它,我已经搜索了stackOverflow,但我无法弄清楚如何在<p>
内搜索。
<input id="search">
<p>Some text content I want</p>
<script>
//script to search the above "p"
</script>
我希望javascript为找到的匹配设置样式。
这是我所拥有的Js Fiddle。
概要
答案 0 :(得分:0)
您可以这样做:
function myfunction(ctrl) {
var TextInsideP = ctrl.getElementsByTagName('p')[0].innerHTML;
}
您的p
标记内容现在位于变量TextInsideP
内,无论您想要什么,都可以使用它们。
答案 1 :(得分:0)
您可以先获取#search元素中第一个p元素的内容,然后执行搜索。将返回搜索元素的字符串位置,如果未找到则返回-1。
var text = document.querySelector('#search p')[0].innerHTML;
var n = text.search("text to find");
if (n !== -1) {
// Found!
} else {
// Not found
}
答案 2 :(得分:0)
如果您要在'p'标签内搜索特定字词,则必须使用选择器抓取它。那么你必须拆分单词串,循环遍历它们并使用indexOf进行搜索(见下文)
var input = document.getElementById('search');
input.addEventListener('keyup', function() {
var val = input.value;
searchExactMatch(val);
searchPartialMatch(val);
})
var p = document.getElementById('test');
var text = p.innerHTML;
var splits = text.split(' ');
function searchExactMatch(value) {
var word = value;
var index = splits.indexOf(word);
if (index > -1) {
console.log('full match with: ', splits[index]);
}
}
function searchPartialMatch(value) {
var word = value;
for (var t = 0; t < splits.length; t++) {
var split = splits[t];
if (split.indexOf(word) > -1) {
console.log('the typed string is a partial match with: ', split);
}
}
}
<p id="test">text goes here</p>
<input id="search" />
答案 3 :(得分:0)
您可以使用document.getElementsBytagName('tagName')
访问打开和关闭代码之间的文本。
<!DOCTYPE html>
<html>
<body>
<p>Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non numquam [do] eius modi tempora inci[di]dunt, ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur?</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
//document.write(document.getElementsByTagName("p")[0].innerText); //Old text from the tag <p>
document.getElementsByTagName("p")[0].innerText = "This works great."; //new text inside tag <p>.
}
</script>
</body>
</html>
答案 4 :(得分:0)
我认为如果您想突出显示内容,则需要将其他内容替换为其他内容。 我的想法如下:使yourSearchWord变粗:
[{
"Name":"March-2016",
"Elements":[
{
"Name":"aa",
"Elements":[
{
"category":"ss",
"Test1":22,
"Test2":33,
"Test3":44,
"Test4":55
},
{
"category":"ssee",
"Test1e":224,
"Test2e":334,
"Test3e":443,
"Test4e":554
}
]
}
]
}]
答案 5 :(得分:0)
我编写了一个函数,当输入中输入的值与p
元素中的字符串完全匹配时,它将突出显示p
元素。
var elements = document.querySelectorAll('p');
var HIGHLIGHT_STYLE_PREFIX = '<span style="background-color:yellow">';
var HIGHLIGHT_STYLE_SUFFIX = '</span>';
document.getElementById('search').addEventListener('input', highlightMatches);
function highlightMatches() {
var queryTerm = this.value.trim();
for (let i = 0; i < elements.length; i++) {
elements[i].childNodes.forEach(function(currentValue) {
if (currentValue.data === queryTerm) {
elements[i].innerHTML = HIGHLIGHT_STYLE_PREFIX + elements[i].innerHTML + HIGHLIGHT_STYLE_SUFFIX;
} else {
if (elements[i].innerHTML.indexOf(HIGHLIGHT_STYLE_SUFFIX) > -1) {
elements[i].innerHTML = elements[i].innerHTML.replace(HIGHLIGHT_STYLE_PREFIX, '').replace(HIGHLIGHT_STYLE_SUFFIX, '');
}
}
});
}
}
&#13;
<input id="search" />
<p>Sed ut perspiciatis</p>, unde
<p>omnis</p> iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo.
<p>Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia</p>
<p>omnis</p>
<p>consequuntur magni dolores eos, qui ratione voluptatem sequi</p>
nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit amet consectetur adipisci[ng] velit, sed quia non numquam [do] eius modi tempora inci[di]dunt, ut labore et dolore magnam aliquam quaerat
<p>voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem</p> ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae
<p>consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur?</p>
&#13;
答案 6 :(得分:-1)
我找到了answer。 感谢所有人回答我的问题!
$(function() {
// the input field
var $input = $("input[type='search']"),
// clear button
$clearBtn = $("button[data-search='clear']"),
// prev button
$prevBtn = $("button[data-search='prev']"),
// next button
$nextBtn = $("button[data-search='next']"),
// the context where to search
$content = $(".content"),
// jQuery object to save <mark> elements
$results,
// the class that will be appended to the current
// focused element
currentClass = "current",
// top offset for the jump (the search bar)
offsetTop = 50,
// the current index of the focused element
currentIndex = 0;
/**
* Jumps to the element matching the currentIndex
*/
function jumpTo() {
if ($results.length) {
var position,
$current = $results.eq(currentIndex);
$results.removeClass(currentClass);
if ($current.length) {
$current.addClass(currentClass);
position = $current.offset().top - offsetTop;
window.scrollTo(0, position);
}
}
}
/**
* Searches for the entered keyword in the
* specified context on input
*/
$input.on("input", function() {
var searchVal = this.value;
$content.unmark({
done: function() {
$content.mark(searchVal, {
separateWordSearch: true,
done: function() {
$results = $content.find("mark");
currentIndex = 0;
jumpTo();
}
});
}
});
});
/**
* Clears the search
*/
$clearBtn.on("click", function() {
$content.unmark();
$input.val("").focus();
});
/**
* Next and previous search jump to
*/
$nextBtn.add($prevBtn).on("click", function() {
if ($results.length) {
currentIndex += $(this).is($prevBtn) ? -1 : 1;
if (currentIndex < 0) {
currentIndex = $results.length - 1;
}
if (currentIndex > $results.length - 1) {
currentIndex = 0;
}
jumpTo();
}
});
});