我无法启动事件处理程序。我在页面中调用JSON,如下所示。然后,我希望能够单击我创建的按钮之一,该按钮将执行“ hello there”警报。它适用于页面上的所有其他元素,但不适用于<button>

有人可以帮忙吗?

test.js

$(document).ready(function() {
  $.getJSON('/api/v1/recipe/?format=json', function(data) {
    $.each(data.objects, function(i, recipe) {
      $('table#recipes').append('<tr><td>' + recipe.title + '</td><td>' + recipe.ingredients + '</td><td>' + recipe.method + '</td><td><button class="btn" type="button" id="rmv">remove</button></td></tr>');
      });
    });

    $('rmv').on('click', function() {
      alert('hello there!');
    });
  });


recipe.html

{% extends 'base.html' %}

{% block content %}
<div class="container-fluid">
  <div class="row-fluid">
    <div class="span6">
      <form action='' method="post">{% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="go baby!">
      </form>
    </div>
    <div class="span6">
      <table class="table table-striped table-bordered" id="recipes">
        <tr>
          <th>Title</th>
          <th>Ingredients</th>
          <th>Method</th>
          <th>Remove</th>
        </tr>
      </table>
    </div>
  </div>
</div>
{% block recipes %}{% endblock recipes %}
{% endblock content %}

最佳答案

您选择器有误,应该是

$('#rmv')


如果要动态附加元素,则应像

$(document).on('click','#rmv',function(e) {
  //handler code here
});


您在ajax成功回调中循环可能会产生具有重复ID的元素,这是错误的,因此@Alnitak提到您可以像修改cde之后切换到类选择器

$.getJSON('/api/v1/recipe/?format=json', function(data) {
  $.each(data.objects, function(i, recipe) {
    $('table#recipes').append('<tr><td>' + recipe.title + '</td><td>' + recipe.ingredients + '</td><td>' + recipe.method + '</td><td><button class="btn rmv" type="button" >remove</button></td></tr>');
  });
});


选择器看起来像

$(document).on('click','.rmv',function(e) {
  //handler code here
});

关于jquery - jQuery On Click不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16022744/

10-09 15:00