$(document).ready(function(){
$("stack").each(function(){
styles = $(this).parse_attr();
$(this).convert_el().css(styles);
});
});
(function($){
$.fn.parse_attr = function(){
if(this.length === 0 ){
return null;
}
tag_types = ["class","id","name"];
css_hash = {};
$.each(this[0].attributes,function(){
attrib = this.name.split(":")
if( !($.inArray(attrib[0],tag_types) >= 0) ){
if($.isNumeric(attrib[1])){
css_hash[attrib[0]] = attrib[1] + "px";
}else{
css_hash[attrib[0]] = attrib[1];
}
}
});
return css_hash;
};
}(jQuery));
(function($){
$.fn.convert_el = function(){
if(this.length === 0 ){
return null;
}
klasses = this.prop("tagName").toLowerCase();
tag_types = ["class","id","name"];
$.each(this[0].attributes,function(){
attrib = this.name.split(":")
if($.inArray(attrib[0],tag_types) >= 0 ){
klasses = klasses + " " + attrib[1].replace(/"/g,"");
}
});
this.replaceWith($("<div class='"+ $.trim(klasses) + "'>" + this.html() + "</div>"));
return this;
}
}(jQuery));
如果我不迭代“stack”元素,它将应用样式,但由于某种原因它会忽略 .css(styles);迭代期间。有什么想法吗?
另外,请不要问我为什么要这样做,我只是尝试通过 jquery 传递不存在的 html 标签来动态开发网页,例如
<stack class:center margin:100 color:red background-color:#FFF></stack>
然后它应该将这些值解析为样式并应用它。
最佳答案
我猜问题出在替换上。原始元素已被删除,因此您无法更改其样式,但 $.fn.convert_el
仍会返回它。
稍微改变一下函数就可以得到想要的结果。
newDiv = $("<div class='"+ $.trim(klasses) + "'>" + this.html() + "</div>")
this.replaceWith(newDiv);
return newDiv;
关于Jquery 不会在循环中分配样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18795285/