0

几个小时以来,我一直在努力解决一个看似简单的问题。我已经编写了一个有效的 REGEX 表达式,但是我希望有一种更优雅的方法来处理 HTML。字符串将被传递给函数,而不是直接在页面中处理内容。看了很多例子后,我觉得我一定做错了什么。我试图在将它保存到我们的数据库之前获取一个字符串并清除它的客户端事件,我认为 jQuery 非常适合这个。

我想要:

Some random text <a href="http://stackoverflow.com" onclick="return evilScripts();">click here</a> and a link with any event type
//to become:
Some random text <a href="http://stackoverflow.com">click here</a> and a link with any event type

这是我的代码

function RemoveEvilScripts(){
    var myDiv = $('<div>').html('testing this <a href="#Foo" onclick="return runMyFunction();">Do it!</a> out');
    //remove all the different types of events
    $(myDiv).find('a').unbind();            
    return $(myDiv).html();
}

我的结果是,onClick 保留在锚标记中。

4

3 回答 3

3

这是一个纯 Javascript 解决方案,它从任何以“on”开头的 DOM 元素(及其子元素)中删除任何属性:

function cleanHandlers(el) {

    // only do DOM elements
    if (!('tagName' in el)) return;

    // attributes is a live node map, so don't increment
    // the counter when removing the current node
    var a = el.attributes;
    for (var i = 0; i < a.length; ) {
        if (a[i].name.match(/^on/i)) {
            el.removeAttribute(a[i].name);
        } else {
            ++i;
        }
    }

    // recursively test the children
    var child = el.firstChild;
    while (child) {
        cleanHandlers(child);
        child = child.nextSibling;
    }
}

cleanHandlers(document.body);​

在http://jsfiddle.net/alnitak/dqV5k/工作演示

于 2012-07-18T21:31:38.927 回答
1

unbind()不起作用,因为您使用的是内联 onclick 事件处理程序。如果您使用 jquery/javascript 绑定单击事件,则可以使用 unbind() 取消绑定事件。要删除任何内联事件,您只需使用removeAttr('onclick')

$('a').click(function(){ //<-- bound using script
    alert('clicked');
    $('a').unbind(); //<-- will unbind all events that aren't inline on all anchors once one link is clicked
});

http://jsfiddle.net/LZgjF/1/

于 2012-07-18T21:07:02.387 回答
-1

我最终得到了这个解决方案,它删除了任何项目上的所有事件。

function RemoveEvilScripts(){
    var myDiv = $('<div>').html('testing this <a href="#Foo" onclick="return runMyFunction();">Do it!</a> out');
    //remove all the different types of events
     $(myDiv)
        .find('*')
        .removeAttr('onload')
        .removeAttr('onunload')
        .removeAttr('onblur')
        .removeAttr('onchange')
        .removeAttr('onfocus')
        .removeAttr('onreset')
        .removeAttr('onselect')
        .removeAttr('onsubmit')
        .removeAttr('onabort')
        .removeAttr('onkeydown')
        .removeAttr('onkeypress')
        .removeAttr('onkeyup')
        .removeAttr('onclick')
        .removeAttr('ondblclick')
        .removeAttr('onmousedown')
        .removeAttr('onmousemove')
        .removeAttr('onmouseout')
        .removeAttr('onmouseover')
        .removeAttr('onmouseup');
    return $(myDiv).html();
}
于 2012-07-19T13:07:41.363 回答