removeAttr在字符串html

removeAttr inside string html

本文关键字:html 字符串 removeAttr      更新时间:2023-09-26

我想从字符串html中删除attr。我有这个代码

 var htm = result.Html;
            $(htm, 'div').each(function () {
                    $(this).removeAttr('ondragover');
                    $(this).removeAttr('ondragleave');
                    $(this).removeAttr('ondrop');
            });
            $('#divLayout').html(htm);

,但问题是字符串保持原来的样子notice: result.Html equal:

    <div class="updiv containertwo" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
    <div id="fchoise" class="detdiv containertwo">
        <div id="df4a6783-beb2-2cdf-0b1d-611c4d7b195f" class="div1" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
    </div>
    <div class="updiv containertwo" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
    <div id="ghchoise" class="containertwo detdiv">
        <div id="932e29b5-b6fe-97f5-d3dc-21768291ec90"  class="lefts" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
        <div id="cfac8011-0e4e-3eba-aaaa-ac36b58b1512"  class="rights" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
    </div>
    <div class="downdiv containertwo" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
    <div id="thchoise" class="containertwo detdiv">
        <div id="3b8b92b3-45f9-54b2-b01a-60b60f65f175"  class="lefts" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
        <div id="c73e2dc9-9980-774b-5d50-c35336d8201d"  class="rights" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>
    </div>
    <div class="downdiv containertwo" ondrop="drop(event)" ondragleave="dragleave(event)" ondragover="allowDrop(event)"></div>

更改jQuery对象不会修改原始字符串,因此需要

var htm = result.Html;
var $tmp = $('<div />', {
    html: htm
});
$tmp.find('div[ondragover]').removeAttr('ondragover');
$tmp.find('div[ondragleave]').removeAttr('ondragleave');
$tmp.find('div[ondrop]').removeAttr('ondrop');
$('#divLayout').html($tmp.html());

演示:小提琴

这很简单,参见:

var $html = $('<div />', {html: result.Html});
$html.find('div').removeAttr('ondragover ondragleave ondrop');
$('#divLayout').html($html.html());

实际操作:http://jsfiddle.net/caio/JWaLc/