【问题标题】:Get input value using htmlfor使用 htmlfor 获取输入值
【发布时间】:2016-07-23 07:52:55
【问题描述】:

完成这样的事情的最佳方法是什么:

html.erb

<!-- inside a loop -->
    <i htmlfor="wish">
        <!-- name or icon -->
    </i>
    <input type="hidden" class="wish-cls" name="wish" value="<%= product.id %>" />
<!-- end loop -->

JavaScript

$(".wish").click(function(e){
  e.preventDefault();
  //var id = document.getElementsByTagName('wish-cls');
  console.log("Clicked: " + e.target.value);
});

如果我点击输入,当没有隐藏时,我会得到值,但是如何使用htmlfor 来实现呢?有可能吗?

【问题讨论】:

  • 请考虑使用有效属性,例如data-id
  • @A.Wolff 哈哈!会的。

标签: javascript jquery html ruby-on-rails


【解决方案1】:

您可以使用 jQuery 属性选择器和next() 方法来执行此操作,如下所示。

$("[data-id=wish]").click(function(e){
    e.preventDefault();

    var value = $(this).next(".wish-cls").val();
    console.log("Clicked: " + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i data-id="wish">Click</i>
<input type="hidden" class="wish-cls" name="wish" value="1000" />

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多