我正在尝试获取动态生成的输入的相应值。换句话说,我有 X 个动态生成的输入;每个输入都绑定(bind)到一个按钮。话虽如此,我希望用户能够收到绑定(bind)到单击的按钮的动态生成的输入的警报。到目前为止我所做的并没有解决这个问题,无论单击什么按钮,都只会生成第一个输入的值。
我有以下代码 - 动态输入和按钮:
<input type="hidden" id="job_id" name="jobIdName" value="{{ job_id }}"> // please note this input is dynamically generated....
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
对于Jquery,我做了以下工作:
$('#get_id_id').each(function(index) {
$(this).click(function() {
var job_ids = $("[name='jobIdName']");
console.log('Job Ids -------------- : ' + job_ids);
});
});
上面的代码一直只生成第一个生成的输入值?有什么想法或建议吗?
我看过一些可能与此类似的帖子,但它们已经很老了;我也在寻找更现代的实现。
最佳答案
将“输入标签”添加到 div 中:
var counter = 0;
$(document).ready(function(){
$("#get_id_id").click(function() {
var divChildren = $(".job_ids").children();
if(counter < divChildren.length){
if(counter == '0'){
console.log($(divChildren).eq(0).val());
}else{
console.log($(divChildren).eq(counter).val());
}
counter++;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class ="job_ids">
<input type="hidden" name="jobIdName" value="Test01">
<input type="hidden" name="jobIdName" value="Test02">
<input type="hidden" name="jobIdName" value="Test03">
<input type="hidden" name="jobIdName" value="Test04">
<input type="hidden" name="jobIdName" value="Test05">
</div>
<button name="get_id_name" class="get_id_class" id="get_id_id" >Show Id</button>
关于javascript - 使用 Jquery 获取 onClick 事件动态生成的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58067194/