使用jQuery通过style属性定位标签并将其更改为带有类的另一个标签

时间:2018-08-29 15:12:47

标签: jquery html

这是我拥有的代码:

<script> 
  $('span style=“text-decoration:underline;"').replaceWith(function() {
    return $('<h3 class=“classSAmple”/>', {
      html: $(this).html()
    }); 
  });
</script>

编辑后,添加了\“: 我需要定位整个范围字符串。

<script>
$("span style=\"text-decoration:underline;\"").replaceWith(function () {
    return $("<h3 class=\"classSAmple\"/>", {
        html: $(this).html()
    });
});</script>

1 个答案:

答案 0 :(得分:2)

首先,字符是无效的JS。您需要改用"双引号字符。

通过内联样式第二个选择元素是一个真正坏主意。如果您完全没有其他选择(将由classid进行选择,甚至只是一个层次选择器),则可以使用attribute selectorfilter()。后者要强大得多。

第三,请注意,在这种情况下,您要检查的确切CSS属性是text-decoration-line,而不仅仅是text-decoration,因为这是其他几条规则的缩写。

最后,当您创建新的h3元素时,如果要提供属性列表,则需要在其中包含 all 个属性。您不能在元素字符串中包含类,然后在对象中包含其他属性。

话虽如此,请尝试以下操作:

var $span = $('span').filter(function() {
  return $(this).css('text-decoration-line') === 'underline';
}).replaceWith(function() {
  return $('<h3 />', {
    'class': 'classSample',
    'html': $(this).html()
  });
});
h3.classSample { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Unaffected</span>
<span style="text-decoration: underline">This is now an h3...</span>
<span>Unaffected</span>