javascript - 如何动态读取输入 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>
解决方案
您可以收听标签的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>
推荐阅读
- javascript - 一键切换 iFrame
- angular - 我如何调用(ngModelChange)中的方法并使用角度应用条件 4+
- git - 为什么 git revert 会给我带来冲突
- angular - 在 Typescript 中将项目添加到接口数组列表
- java - 按顺序发出多个具有不同请求主体的 API 请求
- vba - 如何在 VBA 中的文本框中添加提示横幅/水印?
- python - SyntaxError:打印的语法无效(file=saveto,*args,**kwargs)
- algorithm - 如何找到 XOR 为 0 的最长连续子数组
- jquery - JQuery $('form').serialize() 在 $('div.container').load() 之后不起作用
- c - 我可以直接将共享内存的地址分配给指针吗?