jQuery和jinja2 .data(“”)返回undefined

时间:2017-07-07 11:58:37

标签: 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但没有得到任何东西

2 个答案:

答案 0 :(得分:2)

截至目前的代码; this函数中的display_popup引用window对象,因此它不会返回所需的值。

在内联点击处理程序

中传递当前元素上下文this
<button onclick="display_popup(this)">

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

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

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

<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
});

&#13;
&#13;
$(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);
  }

});
&#13;
<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>
&#13;
&#13;
&#13;

使用.bind()

使用当前元素设置函数的上下文
  

bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值,并在调用新函数时提供任何前面提供的给定参数序列。

&#13;
&#13;
function display_popup() {
  var name = $(this).data("id");
  window.alert(name);
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首先,检查元素和功能。尝试检查HTML并查看您需要的数据是否有价值。在console.log(this)函数上尝试display_popup,您应该会看到按钮。

如果一切正常,请尝试使用$(this).data()。它将返回一个包含元素所有数据的对象。

如果它不起作用(或者这种情况对您更好),请使用:

$(this).attr('data-id')

这将返回data-id属性值。

如果这些都不起作用,请检查您的jquery版本,但我相信attr将正常工作。

---- ---- EDIT

{p} thisundefined函数上为display_popup。您需要使用onclick="display_popup(this)"然后使用该参数来获取元素属性