[英]How can I apply jQuery event to only one input on page without classes and id's
I have more divs on one page and they are all kinda same. 我在一页上有更多的div,它们都差不多。 All of them have text input.
它们都有文本输入。 In javaScript file there is an event where whenever I press enter in input field it makes a new list in div.
在javaScript文件中有一个事件,每当我在输入字段中按Enter时,它都会在div中创建一个新列表。 The problems is when I press enter it makes a new list on all present divs.
问题是当我按Enter时,它将在所有当前的div上创建一个新列表。
$(".container").on("keypress", "input[type='text']", function(key){ if(key.which === 13){ var todoText = $(this).val(); $("ul").append("<li><span><i class='fas fa-trash-alt'></i></span> " + todoText + "</li>"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="grupa"> <h1>To-Do List<span id="form"><i class="fas fa-edit"></i></span></h1> <input type="text" placeholder="Add New Todo"> <ul> <li><span><i class="fas fa-trash-alt"></i></span> Sabah</li> </ul> </div>
$(".container").on("keypress", "input[type='text']", function(key) {
if (key.which === 13) {
var todoText = $(this).val();
$(this).next("ul").append("<li> ... </li>");
// ^-----^---------------- here's your huckleberry
}
});
You might want to grab a parent wrapper element using closest()
instead, to reduce fragility with your markup. 您可能想改为使用
closest()
来获取父包装器元素,以减少标记的脆弱性。 If you add anything between these two this breaks. 如果在这两个之间添加任何内容,则会中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.