问题
Maybe I oversimplified my question in https://stackoverflow.com/posts/20577488/ I left out an important intermediate step. I wanted to:
- create a Javascript string x
- assign x to a jQuery object (right term?)
- perform jQuery stuff on this object
then append it
var x = "<p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p> "; var template = $(x); template.find('p').attr('class','something'); template.appendTo( ".inner" );
回答1:
You need to use filter instead of find. What you are looking for is at the root level so you need to use filter since find will look for descendants of p that are at the root level. Also you can use addClass to add a class unless you want to remove the existing classes.
var x = "<p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p>";
var template = $(x)
template.filter('p').attr('class','something');
//Or you can use
//template.filter('p').addClass('something');
template.appendTo( ".inner" );
Demo
来源:https://stackoverflow.com/questions/20577616/how-to-modify-the-elements-in-an-html-string-before-appending