【问题标题】:How to add attribute without value with Nokogiri如何使用 Nokogiri 添加没有值的属性
【发布时间】:2015-05-22 00:17:21
【问题描述】:

我正在尝试将属性 autoplay 添加到 iframe。 但是,这个属性只是一个标记,它没有值:

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

在 Nokogiri 中添加类似的属性:

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

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

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

Nokogiri 是否有这种方法可以做到这一点,或者我应该删除 /=""/ 并在末尾加上一个正则表达式?

谢谢

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    Nokogiri 不能做你想做的事,开箱即用。

    • 选项 1:使用您的正则表达式解决方案。

    • 选项 2:HTML 语法表明布尔属性可以设置为自己的值,因此在您的代码中这样做是合法且可以的:

      iframe["autoplay"] = "autoplay"
      

      输出:

      <iframe src="..." autoplay="autoplay"></iframe>
      
    • 选项 3:更改 Nokogiri gem 代码。

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

      找到这一行:

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

      并插入自动播放:

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

      现在 Nokogiri 将根据需要将autoplay 视为二进制属性。

      我正在为你的想法创建一个拉取请求,为所有人添加这个功能到 Nokogiri:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 2017-02-04
      • 2015-02-26
      • 2015-05-20
      • 2023-03-27
      • 2011-02-23
      相关资源
      最近更新 更多