如何使用Nokogiri添加没有值的属性

5

我想要给一个iframe添加autoplay属性,但这个属性只是一个标记,没有具体的值:

<iframe src="..." autoplay></iframe>

在Nokogiri中添加属性的方法如下:

iframe = Nokogiri::HTML(iframe).at_xpath('//iframe')
iframe["autoplay"] = ""
puts iframe.to_s

---------- output ----------

"<iframe src="..." autoplay=""></iframe>"

Nokogiri是否有这样的方法来实现这个,还是我应该在结尾处用正则表达式删除“/ =“” /”?谢谢。
1个回答

1
"Nokogiri不能直接实现您想要的功能,需要进一步处理。"
  • Option 1: use your regex solution.

  • Option 2: HTML syntax says that a boolean attribute can be set to its own value, thus this is legal and fine to do in your code:

    iframe["autoplay"] = "autoplay"
    

    Output:

    <iframe src="..." autoplay="autoplay"></iframe>
    
  • Option 3: alter the Nokogiri gem code.

    $ edit nokogiri-1.6.6.2/lib/nokogiri/html/element_description_defaults.rb
    

    Find this line:

    IFRAME_ATTRS = [COREATTRS, 'longdesc', 'name', ...
    

    And insert autoplay:

    IFRAME_ATTRS = [COREATTRS, 'autoplay', 'longdesc', 'name', ...
    

    Now Nokogiri will treat autoplay as a binary attribute, as you want.

    I'm creating a pull request for your idea, to add this feature to Nokogiri for everyone:

    https://github.com/sparklemotion/nokogiri/pull/1291


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接