【问题标题】:Using variable as attribute but with a space?使用变量作为属性但有空格?
【发布时间】:2014-10-25 18:39:05
【问题描述】:

假设我有一个具有 name 属性的对象,例如:'Woodcutters Hut'。如果我尝试将其分配给按钮属性:

$('#possible_constructions').append("<button name=" + object.name + ">" + object.name + "</button>")

按钮书写正确的是整个“Woodcutters Hut”,但名称属性仅包含第一个单词“Woodcutters”。小屋像这样显示在外面:

<button name="Woodcutters" hut>Woodcutters Hut</button>

无论如何要确保属性被正确分配?

【问题讨论】:

  • 使用$('#possible_constructions').append("&lt;button name=" + object.name.replace(/ /g, "_")+ "&gt;" + object.name + "&lt;/button&gt;")将空格替换为下划线name="Woodcutters_hut"
  • @Sharky 我看到这会起作用,但是按钮文本带有下划线 - 无论如何要避免这种情况?
  • @user3317592 为什么name 和文本需要相同?为什么按钮首先需要name
  • 刷新页面以查看我更新的评论

标签: javascript jquery html variables


【解决方案1】:

让 jQuery 为您处理名称值。不要构建字符串。

$("<button></button>", { 
    name: object.name, 
    text: object.name
}).appendTo("#possible_constructions");

尽管重要的是要注意“Woodcutters Hut”不是一个合适的名称。您不应该在名称值中使用空格。相反,您应该考虑将该值重新调整为更合适的值 - 也许通过用下划线替换非字母数字字符:

object.name.replace(/[^\w]/g, "_");

这会将“Woodcutters Hut”转换为“Woodcutters_Hut”。

【讨论】:

    【解决方案2】:

    试试这个,如果可行的话

      $('#possible_constructions').append("<button name='" + object.name + "'>" + object.name + "</button>")
    

    【讨论】:

    • 这没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
    • @Volker E.:但它确实提供了答案!在&lt;button name=''&gt; 中查找单个刻度。
    • 实际上我推荐了可行的解决方案,我的意思是解决没有获得投票和repu的问题,所以我说“试试这个”如果这不起作用我们会尝试其他的东西,但我确信这一点所以没有评论而是将其发布为答案@volker
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2014-11-18
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多