简体   繁体   English

我如何将jQuery事件仅应用于页面上的一个输入而没有类和ID

[英]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
  }
});

Demo 演示

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.

相关问题 如何在不重新加载页面的情况下刷新.one()事件? - How can I make .one() event refresh without page reloading? 如何将jQuery click事件应用于多个ID - How to apply a jQuery click event to multiple ID's 如何对具有不同ID的输入类使用一个函数 - How to Use one function for input classes with diffrent id's 使用jQuery,我如何Ajax将文本加载到多个.class中而不是#id中? - Using jQuery, how can I ajax load text into multiple .classes rather than #id's? 如何仅在一个组件上应用 Semantic UI 的 css? - How can I apply Semantic UI's css only on one component? 我如何只专注于“ input:text”而不触发其绑定的焦点事件处理程序 - How can I only focus in on an “input:text” without triggering its bound focus event handler 如何将 jQuery 函数应用于具有相同 ID 的所有元素? - How can I apply a jQuery function to all elements with the same ID? 如何将一个事件监听器应用于另一个事件监听器? - How can I apply put one event listener of the other? Javascript:如何从JQuery Dialog构造函数中的类描述符访问事件的ID - Javascript: How can I access an event's id from a class descriptor from within a JQuery Dialog constructor 在DOM中,ID不能在“ for”循环中使用,因为ID只能在一页中使用一次,我该如何解决? - In DOM, ID can not be used in “for” loop because ID can only be used once in one page, how can I solve this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM