项目数量与编辑按钮一起显示,单击编辑按钮时每个项目都会在 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 但什么也没得到 p>
最佳答案
从当前代码开始; 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/