繁体   English   中英

如何用按钮控制相关的文本输入元素?

[英]How to control related text input element with a button?

我有一个动态呈现的文本字段+按钮列表。 用户点击按钮,我想在点击按钮时控制输入字段。

我想你可以这样做:

 <input id="1"><button onclick="doSomething(1)">Something</button> <input id="2"><button onclick="doSomething(2)">Something</button> <!--...--> <input id="3"><button onclick="doSomething(3)">Something</button>

但是想知道是否有不同且更复杂的解决方案,因为我正在修改的代码将匿名函数传递给 onclick,而我无法像上述方法那样传递唯一 ID。

这在 vanilla Javascript 中很容易实现(就像大多数事情一样)。 这里不需要 jQuery 开销。

 let buttons = [...document.getElementsByClassName('inputbutton')] function doSomething(i) { console.log(i); } for (const button of buttons) { button.addEventListener('click', (e) => { const i = e.target.previousSibling.id doSomething(i); }) }
 <input id="1"><button class="inputbutton" type="button">Something</button> <input id="2"><button class="inputbutton" type="button">Something</button> <!--...--> <input id="3"><button class="inputbutton" type="button">Something</button>

如果您像下面这样修改动态 HTML 并添加此 jQuery,您将能够访问前一个输入字段的值。

 var buttons = $(".inputs-and-buttons #button-after-input-field"); buttons.click(function() { console.log($(this).prev("input").val()); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="inputs-and-buttons"> <input id="1" value="1"><button id="button-after-input-field">Something</button> <input id="2" value="2"><button id="button-after-input-field">Something</button> <!--...--> <input id="3" value="3"><button id="button-after-input-field">Something</button> </div>

您可以为带有索引或行号的输入字段和按钮生成动态 Id,也可以为行号添加自定义属性,如下所示。

您也可以为文本框和按钮生成具有特定 Id 的动态相关控件。 例如 txtFirstName_1、txtLastName_1、btnAdd_1。 这里的文本框和按钮由下划线"_"后的 id 和数字区分。

 $(function(){ // Register click on button //here you can pass specific class name for button if all are have same functionality $("button").click(function(e){ console.log(this); var btnId=$(this).attr("id"); //console.log(btnId); // Way 1 //Split btnId with "_" eg btn_1 will splited with ["btn","1"] var rowIndex=btnId.split("_")[1]; console.log(btnId.split("_"),rowIndex); $("#txt_"+rowIndex).val("Upate value by btn"+rowIndex); // Or fetch value // Way 2 // You can directly use custom attribute data-row and do your work var rowIndex1=$(this).attr("data-row");//$(e).prop("data-row"); console.log(rowIndex1); //$("#txt_"+rowIndex1).val("Upate value"); // Or fetch value }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input id="txt_1" data-row="1"><button id="btn_1" data-row="1">Something</button> <input id="txt_2" data-row="2"><button id="btn_2" data-row="2">Something</button> <input id="txt_3" data-row="3"> <button id="btn_3" data-row="3">Something</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM