2012-01-10 2 views
1

JQuery를 사용하여 모든 단일 태그를보고 싶습니다.HTML 코드 문자열을 사용하면 모든 태그를 검토하고 모든 "이벤트"속성을 제거하려면 어떻게해야합니까?

해당 태그의 속성이 "on"으로 시작하는 경우 해당 속성을 완전히 제거하십시오.

나는 방법을 알고 루프에 모든 태그를 통해 :

newvalue = $('<div>' + value + '</div>').find('*').each(function() { 
}).html(); 

하지만, 어떻게 모든 속성을 통해 I에게 루프를하고 "의"로 문자열과 일치?

답변

1

HTML 접두사의 actuall 속성이 아니고 이벤트 처리기를 통해 참조하기 때문에 모든 On 접두어를 볼 수 없습니다.

하지만이 요소에 바인딩 된 모든 이벤트를 볼 수 있습니다.

는 는

당신은 사용해야합니다 (각 기능에)

$(this).data('events'); 

예 : 문자열 또는 실제 DOM 작업을하는 경우

귀하의 예제에서
$.each($("#Myel").data("events"), function(i, e) { 
    alert(i); 
}); 
1

, 잘 모르겠어요 노드. 그것의 문자열을 가정, 뭔가 같은 :

var 
    value = '<div onclick=""><span onfocus="" class=""><img onload="" /></span><a onclick=""></a></div>', 
    newvalue; 

newvalue = $('<div>' + value + '</div>').find('*').each(function() { 
    var self = this; 
    $.each([].slice.call(this.attributes, 0), function (idx, attr) { 
    if (attr.nodeName.substr(0, 2).toLowerCase() === 'on') { 
     $(self).removeAttr(attr.nodeName); 
    } 
    }); 
}).end().html(); 

console.log(newvalue); 
0
newvalue = $('<div>' + value + '</div>').find('*').each(function() { 
    // current element 
    var thiz = $(this); 
    // attributes of element 
    var atts = thiz.get(0).attributes; 
    for (var i = 0; i < atts.length; i++) { 
    var attrName = atts[i].name.trim(); 
    // ignore attribute which does not start with "on" 
    if (attrName.toLowerCase().indexOf("on") != 0) 
     continue; 
    // remove 
    thiz.removeAttr(attrName); 
    } 
}).html(); 

편집 : 사용 DOM은

newvalue = $('<div>' + value + '</div>').find('*').each(function() { 
    // attributes of element 
    var atts = this.attributes; 
    for (var i = 0; i < atts.length; i++) { 
    var attrName = atts[i].name.trim(); 
    // ignore attribute which does not start with "on" 
    if (attrName.toLowerCase().indexOf("on") != 0) 
     continue; 
    // remove 
    this.removeAttribute(attrName); 
    } 
}).html(); 
+2

'var에 thiz는 $ (이) = 기능; var atts = thiz.get (0) .attributes;'처음에는 jQuery 객체를 만든 다음'get (0)'을 사용하여 다시 * 빠져 나간다. 'var atts = this.attributes;'는 동일합니다. – Yoshi

+0

@ Yoshi, 제 연습은 정의 된'thiz'와 상호 작용하는 코드를 작성한 후에 루프 안의 첫 번째 줄에서'thiz' jQuery 객체 변수를 만드는 것입니다. 그냥 습관, 그리고이 질문에 좋지 않아. –

관련 문제