开发者

Is there a way to 'search n replace fill' HTML with jQuery?

开发者 https://www.devze.com 2023-01-13 05:34 出处:网络
Just a small question. Say I have the following HTML: <div class=\"foo\"> {text} </div> Now we also have a JS array with 10 entries, all with a key \'text\'. I w开发者_JS百科ant to use

Just a small question. Say I have the following HTML:

<div class="foo">
    {text}
</div>

Now we also have a JS array with 10 entries, all with a key 'text'. I w开发者_JS百科ant to use the snippet above as a template (snippet resides in jQuery-able webpage) for the array. Array entry goes in, HTML comes out. Here's the tricky part: I want to replace {text} with the text key from the array entry.

And all with jQuery of course ;-).

Best regards,

Reinder


Try it out: http://jsfiddle.net/WZ2Vk/

(Requires jQuery 1.4 or later)

var newText = {
    text: "some new text",
    othertext: "some other new text"
}

$('div.foo').text(function(i,txt) {
    var key = txt.match(/\{([^}]+)\}/)[1];
    return newText[key];
});

You didn't give the structure of the Array, but I assume you're using it in a manner better suited for an Object. In the example above, I used and Object instead of an Array. Will work just fine with an Array.

Same example but with an Array: http://jsfiddle.net/WZ2Vk/1/

If you're replacing with actual HTML content, then change .text() to .html().

http://jsfiddle.net/WZ2Vk/2/

0

精彩评论

暂无评论...
验证码 换一张
取 消