2013-10-14 46 views
0

这可能是一个非常简单的问题,但我对Nokogiri非常陌生,并且很想超越这个小小的障碍。使用Nokogiri编辑不是课程或编号的div标签

如何使用Nokogiri将contenteditable =“true”替换为false或将其完全删除?

<div contenteditable="true"> 

谢谢!

+0

也许同样的问题http://stackoverflow.com/questions/610473/nokogiri-rubygem-find-and-replace-html-tags – hawk

+0

你真的需要表现出一定的代码,所以我们知道你至少尝试自己解决这个问题。 – pguardiario

回答

0

其设置为false:

doc.search('div[contenteditable=true]').each{|div| div[:contenteditable] = 'false'} 

删除它们:

doc.search('div[contenteditable=true]').remove 
+0

我接受了这个因为它只用那一行代码完成了工作(将其设置为false)。删除删除了整个div,我只想删除contenteditable =“true”部分。 –

+0

在这种情况下:'doc.search('div [contenteditable = true]')。each {| div | div.attributes [ 'CONTENTEDITABLE']。除去}' – pguardiario

0

这里是完全使用引入nokogiri当你想删除的方法:

require 'nokogiri' 

doc = Nokogiri::HTML.parse('<div contenteditable="true">') 
doc.at('div') 
# => #(Element:0x504911a { 
#  name = "div", 
#  attributes = [ 
#  #(Attr:0x5048db4 { name = "contenteditable", value = "true" })] 
#  }) 
node=doc.at('div') 
node 
# => #(Element:0x504911a { 
#  name = "div", 
#  attributes = [ 
#  #(Attr:0x5048db4 { name = "contenteditable", value = "true" })] 
#  }) 

node.delete('contenteditable') 
node 
# => #(Element:0x504911a { name = "div" }) 

这里有一个方法,当你想更换contenteditable="true"false引入nokogiri

require 'nokogiri' 

doc = Nokogiri::HTML.parse('<div contenteditable="true">') 
doc.at('div') 
# => #(Element:0x495cb2c { 
#  name = "div", 
#  attributes = [ 
#  #(Attr:0x495c88e { name = "contenteditable", value = "true" })] 
#  }) 
node=doc.at('div') 
node.to_s 
# => "<div contenteditable=\"true\"></div>" 
node['contenteditable']=false 
node.to_s 
# => "<div contenteditable=\"false\"></div>" 

Nokogiri::XML::Node保存所有它的属性名称/值作为键/值对Hash。这里的是一个例子:

require 'nokogiri' 

doc = Nokogiri::HTML.parse('<div contenteditable="true" class = "foo">') 
node=doc.at('div') 
node.keys 
# => ["contenteditable", "class"] 
node.values 
# => ["true", "foo"] 

因此,如果要更改的节点使用Nokogiri::XML::Node#[]=的属性的值(这是如Hash#[]=),或者如果要删除该节点的特定属性,请使用Nokogiri::XML::Node#delete(与Hash#delete相似)。

从评论我将如何检查是否股利却有contenteditable属性, ..

有可能使用方法Nokogiri::XML::Node#key?

require 'nokogiri' 

doc = Nokogiri::HTML.parse('<div contenteditable="true" class = "foo">') 
node=doc.at('div') 
node.key?('class') # => true 
node.key?('foo') # => false 
node.delete('class') if node.key?('class') 
node.delete('class') if node.key?('foo') 
node.to_s 
# => "<div contenteditable=\"true\"></div>" 
+1

太棒了!如何检查div是否真的具有contenteditable属性?在整个文档中只有少数人拥有它们,并且我猜如果我们试图在它们不存在时删除它们,它会触发错误? –

+0

@NicholasJohnMartin看到我的更新.. :) –

+0

非常感谢您的深入介绍! –