【问题标题】:Passing div names with spaces to Vue将带有空格的 div 名称传递给 Vue
【发布时间】:2018-01-17 19:18:31
【问题描述】:

我有一个表,我在其中使用 Vue 为 div 动态创建 ID。代码如下所示:

  <table>
    <tbody>
      <tr v-for="(group, index) in groups" >
        <td>

          <a data-toggle="collapse" :href="'#users-in-'+encodeURIComponent(group.gname)" aria-expanded="false" :aria-controls="'users-in-'+encodeURIComponent(group.gname)" v-text="group.gname"></a>

          <div class="collapse" :id="'users-in-'+encodeURIComponent(group.gname)">
            <p>some stuffs</p>
          </div>

        </td>
        <td>
          <p>Some other stuff</p>
        </td>
      </tr>
    </tbody>
  </table>

这个想法是为每个组动态生成#users-in-someGroupName div 名称。上面的例子效果很好,但是当我在组名中有空格时它会崩溃。在控制台中我得到 JQuery 错误:

Error: Syntax error, unrecognized expression: #users-in-some%20group%20with%20space

我添加了encodeURIComponent 以减轻它,但似乎 Vue/JQuery 无法处理这个问题。如何在 div 名称中传递空格?

【问题讨论】:

  • 与 HTML 相关联的 jQuery 代码是什么?
  • 没有显式的 jQuery 代码,表格位于窗格内,而窗格位于选项卡内。不过,它们都是基于 Bootstrap 构建的。堆栈跟踪仅指 jQuery 和 Bootstrap 代码。

标签: javascript jquery html vue.js vuejs2


【解决方案1】:

虽然id in HTML 5 在字符方面几乎不受限制,但看起来 Bootstrap 确实希望它们是 HTML-4 compliant

而不是encodeURIComponent(用其他特殊字符替换特殊字符),写一个函数到Replace special characters in a string with _ (underscore)

【讨论】:

  • 非常感谢!我试图避免这种情况(因为它会稍微影响我的后端和数据库),但这似乎是唯一的方法。我在文档中错过了这个。
【解决方案2】:

我认为您还可以借助计算属性将空格转换为下划线。

var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // a computed getter
    underScoreName: function (name) {
      return name.split(' ').join('_')
    }
  }
})

您可以使用这个 underScoreName 计算属性将空格更改为下划线。

<table>
    <tbody>
      <tr v-for="(group, index) in groups" >
        <td>

          <a data-toggle="collapse" :href="'#users-in-'+underScoreName(group.gname)" aria-expanded="false" :aria-controls="'users-in-'+underScoreName(group.gname)" v-text="group.gname"></a>

          <div class="collapse" :id="'users-in-'+underScoreName(group.gname)">
            <p>some stuffs</p>
          </div>

        </td>
        <td>
          <p>Some other stuff</p>
        </td>
      </tr>
    </tbody>
  </table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2020-11-02
    • 2010-12-19
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多