javascript - jQuery 和 jinja2 .data ("")返回未定义

标签 javascript jquery django django-templates jinja2

项目数量与编辑按钮一起显示,单击编辑按钮时每个项目都会在 jQuery 函数中检索按钮的数据,但我得到的是未定义的而不是数据 ID

<div>
{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id  btn_id="btn"|concatenate:stock.id %}
    <div id="{{ id }}">
    {{ stock.entry_date}}
    {{ stock.supplier }}
    {{ stock.amount }}
    {{ stock.remaining }}
        <button id="{{ btn_id }}" type="submit" data-id="{{stock.id}}" onclick="display_popup()" style="position: absolute; right:0;" >edit</button>
    <hr>
    </div>
    <br>
    {% endwith %}
{% endfor %}
</div>

而不是 {{stock.id}} 我还尝试传递其他字符串,但仍然未定义

<script type="text/javascript">
     function display_popup() {
         var name = $(this).data("id");
            window.alert(name);
    }

</script>

除了 .data() 之外,还尝试了其他类似 .text() .Val 但什么也没得到

最佳答案

从当前代码开始; display_popup 函数中的 this 引用了 window 对象,因此它没有返回所需的值。

在内联点击处理程序中传递当前元素上下文this

<button onclick="display_popup(this)">

脚本,接受它作为参数并使用它来获取数据

 function display_popup(elem) {
     var name = $(elem).data("id");
     window.alert(name);
}
<小时/>

但是,我建议您使用不显眼的事件处理程序。为按钮分配一个公共(public)类。

<button class="edit" data-id="{{stock.id}}"  >edit</button>

脚本

$(function(){
  $('.edit').on('click', display_popup); //this will set as context so you existing method will work
});

$(function() {
  $('.edit').on('click', display_popup); //this will set as context so you existing method will work

  function display_popup() {
    var name = $(this).data("id");
    window.alert(name);
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="edit" type="submit" data-id="1">edit</button>

<小时/>

使用 .bind() 设置当前元素的函数上下文

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

function display_popup() {
  var name = $(this).data("id");
  window.alert(name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="submit" data-id="1" onclick="display_popup.bind(this)()">edit</button>

关于javascript - jQuery 和 jinja2 .data ("")返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44970224/

相关文章:

python - 类型错误 : cannot unpack non-iterable int object in Django views function

python - 将 python 列表传递给 django 模板

javascript - 如何使用 javascript 从 div 内容中删除单词/字符串

javascript - 为什么在几乎没有阻塞操作的情况下,事件循环从 JavaScript 开始就存在

javascript - Knockout 共享绑定(bind)处理程序

javascript - 除了 class、id 和 text 之外,我还能如何在 jQuery 元素中传递变量?

javascript - 将数组的元素附加到字符串

php - 如何根据国家/地区更改日期格式

javascript - 无法从 .resize() 中调用 jQuery 函数

python - Serializer 上的 SerializerClass 字段从主键保存