如何使用Hpricot从html中删除事件属性?

时间:2010-01-05 07:42:49

标签: ruby-on-rails ruby hpricot

我想从html中删除dom events属性列表?这该怎么做?像:

before = "<div onclick="abc" >abc</div>"
after = clean_it(before) // after => "<div>abc</div>"       


DOM_EVENT_TO_BE_REMOVE = "onclick|ondblclick|onerror|onfocus|onkeydown"  // i want to remove these events

// i want to do it like this
def clean_it(html)
  doc = Hpricot(html)    
  doc.search(DOM_EVENT_TO_BE_REMOVE).remove_attribute(DOM_EVENT_TO_BE_REMOVE) 
  doc.to_s
end

感谢。

1 个答案:

答案 0 :(得分:2)

使用“remove_attr”,例如:

doc.search("[@onclick]").remove_attr("onclick")

因此,为您的文档执行以下操作:

DOM_EVENT_TO_BE_REMOVE = ["onclick", "ondblclick", "onerror", "onfocus", "onkeydown"]
DOM_EVENT_TO_BE_REMOVE.each do |de|
    doc.search("[@#{de}]").remove_attr(de)
end