简体   繁体   English

输入keyup jQuery函数不起作用

[英]input keyup jquery function does not work

I have a situation like the one below: 我有一种类似以下的情况:

 var value = document.getElementById("value").value; if (value = 'a') { ('.setting').append('<input type="text" name="name" placeholder="carname">'); } elseif(value = 'b') { ('.setting').append('<input type="text" name="name" placeholder="fruitname">'); } $(document).ready(function() { $("input[name=name]").keyup(function() { alert("The text has been changed."); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="username" placeholder="your name"> <select id="value"></select> <div class="setting"></div> 

The problem I have is that when I change the input the alert does not trigger. 我的问题是,当我更改输入时,警报不会触发。 Does anyone know were am I messing up? 有人知道我在搞砸吗?

You're trying to select an input whose name property is "name" , but the value you set in your HTML is name="username" . 您试图选择name属性为"name"input ,但是在HTML中设置的值为name="username"

$(document).ready(function(){
    $("input[name='username']").keyup(function(){
        alert("The text has been changed.");
    });
});

A better way yet is to give your input a unique id and select by that, so you don't have to use an attribute selector: 更好的方法是为您的输入提供唯一的id并以此进行选择,因此您不必使用属性选择器:

<input id="usernameInput" type="text" name="username" placeholder="your name">
$("#usernameInput").keyup(function(){ ... });

The $ is missing from ('.setting') , you should use .on to catch events of dynamically created elements and it's better to use it with classes, also use == or more likely === for conditions. $ ('.setting') .on ('.setting')缺少$ ,您应该使用.on来捕获动态创建的元素的事件,最好将其与类一起使用,还应将==或更可能是===用于条件。

Live example 现场例子

Your code modified: 您的代码已修改:

<input type="text" name="name" class="example" placeholder="your name">
<select id="value"></select>
<div class="setting"></div>

<script>
  var value = document.getElementById("value").value;
  if(value==='a'){
    $('.setting').append('<input type="text" name="name" class="example" placeholder="carname">');
  }

  else if(value==='b'){
    $('.setting').append('<input type="text" name="name" class="example" placeholder="fruitname">');
  }
</script>

<script>
 $(document).ready(function(){
   $('body').on('keyup', '.example', function() {
     alert("The text has been changed.");
   });
 });
</script>

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

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