且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery DOM解析器?

更新时间:2023-02-26 11:12:28

将内容作为HTML字符串,这里将是一种区分大小写的方式它具有上面显示的功能的肉体上的示例变量。

  var content =< div>但是是一个div!< / div>< p>这是一个段落,你喜欢这段吗?< / p>; 

//附加到div以确保有一个***标签。
var html = $(< div>< / div>)。append(content).html();

// keywordList是一个div的选择器,包含代表内容的项目的跨度
$(#keywordList)。find(span)。filter(function(){
return html.indexOf($(this).html())!= -1;
})。each(function(){
$(this).html(< span class ='highlight'>+ $(this).html()+< / span>);
});

以下是测试HTML:

 < div id =keywordList> 
< span>段< / span>< br />
< span> span< / span>< br />
< span> ul< / span>< br />
< span> div< / span>< br />
< span> ol< / span>< br />
< span> table< / span>< br />
< / div>

您可以查看此操作


I've got a jQuery script that calls out to the Yahoo Boss API and retrieves a list of keywords related to a seed keyword phrase. Once the script has the keyword list, I'm then writing these keywords to the screen, each in a span tag to allow the user to add them to their post/page content (WordPress)

The script is working great and now I'd like to enhance it a bit so that I can highlight a keyword in the listing if it already appears inside the content being edited.

What I need to do is to parse the contents of a textarea (the WordPress content editor) and for every matching term that exists in the content, I need to apply a special style to the keyword's span tag in the LSI list.

I'm looking for your suggestions on resources or examples on using javascript and jQuery to parse the innerText (aka content sans html tags) content of the WordPress content editor.

For example, I have a button which when clicked, executes the following jQuery which pulls a listing of keywords, then adds them to a string "result" to write them to the screen...

for (key in keywords){if (keywords[key] > 5) result += '<span>' + key + ',</span>';}

So what I need to do is to evaluate, for each keyword returned inside the loop, if it appears in the content editor (jQuery('#content').html()) and if so, I need to add a highlight class to the span. Otherwise, leave it as is.

Given the contents as an HTML string, here would be one case-sensitive way to do it, with filled-in example variables shown above the meat of the function.

var content = "<div>But this is a div!</div><p>This is a paragraph.  Do you like this paragraph?</p>";

// append to a div to make sure there's a top-level tag.
var html = $("<div></div>").append(content).html();

// keywordList is a selector for a div containing spans of items representing the contents
$("#keywordList").find("span").filter(function() {
    return html.indexOf($(this).html()) != -1;
}).each(function() {
    $(this).html("<span class='highlight'>" + $(this).html() + "</span>");
});

Here's the test HTML:

<div id="keywordList">
    <span>paragraph</span><br />
    <span>span</span><br />
    <span>ul</span><br />
    <span>div</span><br />
    <span>ol</span><br />
    <span>table</span><br />
</div>

You can see this in action.