嗨,我有下面的html代码
<div id="im" style="width:20px; color:red;" >12</div>我需要将这个html结构<div id="im" style="width:20px; color:red;" >转换成一个变量。我是怎么得到这个的?
要获取文本或div中的内容,我们可以使用
$( "#im" ).html();但我想要的是htm结构,而不是内容。请帮帮忙。
编辑
我知道我们可以使用$( "#im" ).prop('outerHTML');
从这个结果我如何得到width?
我知道我们可以使用.css(“宽度”),但是我需要从prop('outerHTML')获得这个信息。
请帮帮忙。
发布于 2017-01-16 07:43:15
您可以从DOM元素对象的outerHTML属性获得它。可以使用索引获取来自jQuery objec的DOM元素t。
$("#im")[0].outerHTML更新1 :从属性获取宽度,使用attr()方法获取属性值,使用String#match方法从字符串中使用regex获取样式属性值。
console.log(
$('#im').attr('style').match(/width\s?:([^;]+)/)[1]
)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="im" style="width:20px; color:red;">12</div>
更新2 :,尽管您可以使用css()方法获得使用属性计算的结果。
console.log(
$('#im').css('width')
)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="im" style="width:20px; color:red;">12</div>
更新3 :从字符串中获取它,用jQuery包装它,并执行同样的操作。
console.log(
$($('#im')[0].outerHTML).css('width')
)
// or
console.log(
$($('#im')[0].outerHTML).attr('style').match(/width\s?:([^;]+)/)[1]
)<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="im" style="width:20px; color:red;">12</div>
https://stackoverflow.com/questions/41671565
复制相似问题