首页 > 解决方案 > 如何动态读取输入 ID 并将其值放入文本 jQUery

问题描述

我正在尝试读取 的值input并在标签中更新它P,值将是动态的。

更新:在每次更新点击时,值应在段落下方替换

input {
  display: block;
  margin-bottom: 10px;
}
<input id="Q_Star1_Text" type="text" name="starValue" value="Value One"> - <a id="test1" href="javascript:;">Update</a>
<input id="Q_Star2_Text" type="text" name="starValue" value="Value Two"> - <a id="test2" href="javascript:;">Update</a>
<input id="Q_Star3_Text" type="text" name="starValue" value="Value Three"> - <a id="test3" href="javascript:;">Update</a>
<input id="Q_Star4_Text" type="text" name="starValue" value="Value Four">- <a id="test4" href="javascript:;">Update</a>
<input id="Q_Star5_Text" type="text" name="starValue" value="Value Five"> - <a id="test5" href="javascript:;">Update</a>

<p class="final-text">Replace This</p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
  $("#test").on('click', function() {
    var inputVal = $("#Q_Star1_Text").val();
    $(".final-text").text(inputVal);
  });
</script>

标签: javascriptjqueryhtml

解决方案


您可以收听标签的click事件,a并在单击时input使用以下方法获取上一个的值prev()

$("a[id^=test]").on('click', function() {
  var value = $(this).prev('input[id^=Q_Star]').val();
  $('.final-text').text(value);
});
input {
  display: block;
  margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="Q_Star1_Text" type="text" name="starValue" value="Value One"> - <a id="test1" href="javascript:;">Update</a>
<input id="Q_Star2_Text" type="text" name="starValue" value="Value Two"> - <a id="test2" href="javascript:;">Update</a>
<input id="Q_Star3_Text" type="text" name="starValue" value="Value Three"> - <a id="test3" href="javascript:;">Update</a>
<input id="Q_Star4_Text" type="text" name="starValue" value="Value Four">- <a id="test4" href="javascript:;">Update</a>
<input id="Q_Star5_Text" type="text" name="starValue" value="Value Five"> - <a id="test5" href="javascript:;">Update</a>

<p class="final-text">Replace This</p>


推荐阅读