2011-10-16 22 views
0

我試圖從HTML <body>字符串獲取所有內聯事件標記的列表,我如何能夠做到這一點?從HTML字符串獲取所有內聯事件

例子:

<a onclick='foo()'></a> 

我想提取onclick='foo()'

REGEX或其他選擇可能嗎?

+0

yes ** [請看這裏](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)** – qwertymk

+0

是,我讀過,想知道如果任何替代品都可以。 雖然內聯方面的事件非常穩定,所以REGEX可能會起作用。 – Trevor

+0

你可以遍歷每個元素並訪問它的'onXXXXX'屬性... –

回答

0

這是一個。該事件的事情將是第1組:

<\w+[^>]+(on[a-z]+=["'][^"']+["'])[^>]*> 
+0

對不起,但你的REGEX不起作用。 – Trevor

+0

這很奇怪,適合我。你是否嘗試過使用大小寫不敏感的搜索? – Tetaxa

+0

如果問題是組,那麼你可以使用一些更天真的正則表達式,比如'(on [az] + = [「'] [^」'] + [「'])(?= [^>] * >)' – Tetaxa

0

你應該讓瀏覽器做解析,比如像這樣:

var attributes = Array.prototype.slice.call(doc.body.attributes); 
for (var i = 0; i < attributes.length; i++) { 
    if (/^on/.test(attributes[i].name)) { 
     console.log(attributes[i].name, attributes[i].value); 
    } 
} 

var doc = document.implementation.createHTMLDocument(''); 
doc.documentElement.innerHTML = '<body onload="alert(1)"></body>'; // your string here 

然後使用DOM方法得到on*屬性

+0

我同意你應該使用DOM或者某個庫,如果你真的在瀏覽器中的話,Otoh,如果你正在通過內聯事件處理程序的代碼來替換它們,那麼正則表達式可能會更容易。 – Tetaxa

+0

我需要這個的原因是我在node.js中做了這個,具有諷刺意味的是jsdom模塊忽略了內聯事件。 – Trevor