【问题标题】:How to pass text from view to javascript如何将文本从视图传递到javascript
【发布时间】:2016-06-26 09:03:19
【问题描述】:

您好,我对RailsJavascript 有疑问。这是我的桌子。

<table>
  <thead>
    <tr>
      <th>No</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
      <tr id="adminrow">
        <td>
          1
        </td>
        <td>
          <a href="#" id="select_name">John</a>
        </td>
      </tr>
      <tr id="adminrow">
        <td>
          2
        </td>
        <td>
          <a href="#" id="select_name">Alex</a>
        </td>
      </tr>
      <tr id="adminrow">
        <td>
          3
        </td>
        <td>
          <a href="#" id="select_name">Paul</a>
        </td>
      </tr>
  </tbody>
</table>

我的JS

$('#select_name').click(function(event){
    var username = $("#select_name").text();
    console.log(username);
});

我的表中有很多名字,但JS 在控制台中打印了名字。如何将表格中的每个名称打印到控制台?

【问题讨论】:

  • 你想解决什么问题?
  • 在 js 文件中使用这个var username = $(this).text() 希望它能工作
  • @uzaif 我的意思是表数据在循环中,我希望每个数据都传递给 JS。 Example Name is like John, Alex, Wade, Paul... var username is like John, Alex, Wade, Paul。但现在它只打印了约翰。

标签: javascript ruby-on-rails haml


【解决方案1】:

您正在每个循环中创建具有相同select_name ID 的 N 个链接(按用户数)。您的 javascript 很困惑,该选择哪一个。尝试将用户 ID 添加到您的 html select_name id 并相应地调整您的 javascript。你的另一个 ID adminrow 也一样。

或者只需将您的 select_name 更改为类而不是 id:

 ....
 %a{:href=>"#", :class=>"select_name"}=u.firstname
 ....
 $('.select_name').click(function(event){ ....

好的,我正在为您附上完整的代码。对我来说它工作得很好。例如。单击相应链接后仅打印名称:

<table>
<thead>
  <tr>
    <th>No</th>
    <th>Name</th>
  </tr>
</thead>
<tbody>
    <tr class="adminrow">
      <td>
        1
      </td>
      <td>
        <a href="#" class="select_name">John</a>
      </td>
    </tr>
    <tr class="adminrow">
      <td>
        2
      </td>
      <td>
        <a href="#" class="select_name">Alex</a>
      </td>
    </tr>
    <tr class="adminrow">
      <td>
        3
      </td>
      <td>
        <a href="#" class="select_name">Paul</a>
      </td>
    </tr>
</tbody>
</table>

<script type="text/javascript">
  $('.select_name').click(function(event){
    var username = $(this).text();
    console.log(username);
  });
</script>

【讨论】:

  • 我该怎么做?
  • @NeoTeo:调整了答案。
  • 谢谢,但它同时打印了所有数据。我想通过单击名称打印每个名称
  • @NeoTeo:正如@uzaif 在 cmets 中指出的那样,您应该使用var username = $(this).text()。我以为你已经发现了这个错误。
  • @NeoTeo:我刚刚将完整代码添加到答案中。测试表明它工作得很好。再次检查/比较您的代码。
猜你喜欢
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 1970-01-01
相关资源
最近更新 更多