Use jquery to write an ID based on text in a span tag
I am not sure if this is even possible, with that said... below is a sample of HTML I am working with. I want to, with jQuery, grab the product name and insert it as an ID on the paired span tag with the class "support", replacing spaces with underscores.
<div><span class="title">Product1 Name</span> <span class="support"></span></div>
<div><span class="title">Product1 Name</span> <span class="support"></span></div>
<div><span class="title">Product1 Name</span> <span class="support"></span></div>
<div><span class="title">Product1 Name</span> <span class="support"></span></div>
Below would be the desired HTML that jQuery would modify. Is this possible?
<div><span class="title">Product1 Name</span> <span class="support" id="product1_name"></span> </div>
<div><span class="title">Product2 Name</span> <span class="support" id="product2_name"></span> </div>
<div><span class="title">Product3 Name</span> <span class="support" id="product3_name"></spa开发者_StackOverflown> </div>
<div><span class="title">Product4 Name</span> <span class="support" id="product4_name"></span></div>
Yup.
$('span.title').each(function ()
{
var $this = $(this),
id = $this.text().toLowerCase().replace(/ /g, '_');
$this.next().attr('id', id);
});
Demo!
This could very well create elements with duplicate IDs, however. Not good.
something like:
(".title").each(function() {$(this).next(".support").attr("id",$(this).html().replace(" ","_"));});
didn't check it but it should work, hope I got the parenthesis count right in the end...
精彩评论