javascript $(this).data() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21926263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript $(this).data() not work
提问by shanto
I wrote some code that sends a value to a database using ajax. However, my alert box shows undefined
for the value. I don't understand what my problem is.
我编写了一些代码,使用 ajax 将值发送到数据库。但是,我的警报框显示undefined
了该值。我不明白我的问题是什么。
<script>
$(document).ready(function(){
$(document).on('click', '#publish', function(){
var status = $(this).data('data-pid');
alert(status);
$.ajax
({
url: 'update_about_status.php',
data: {"statusValue": status},
type: 'post',
success: function(result)
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
});
</script>
print'<button type="button" id="publish" class="btn btn-info" data-pid="'.$cd[$i][3].'">Make Publish</button>';
回答by Arun P Johny
When you use the data()api, there is no need to have the data-
prefix to read the data-*
attribute value - see data-html5
当你使用data()api时,不需要有data-
前缀来读取data-*
属性值——见data-html5
var status = $(this).data('pid');
If you are using .attr()then you need to use the complete attribute name like
如果您使用.attr()那么您需要使用完整的属性名称,如
var status = $(this).attr('data-pid');
回答by Adil
You do not have to give data-
in parameter of data()
function but you have to give only give pid
, The data-
is used to identify the data attributes.
您不必data-
在data()
函数的参数中给出pid
,而只需给出 give ,data-
用于标识数据属性。
var status = $(this).data('pid');
Embedding custom non-visible data with the data-* attributes
A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters, reference.
使用 data-* 属性嵌入自定义的不可见数据
自定义数据属性是没有命名空间的属性,其名称以字符串“data-”开头,连字符后至少有一个字符,与 XML 兼容,并且不包含大写 ASCII 字母,参考。
回答by drunkcoder
can you try changing to:
您可以尝试更改为:
var status = $(this).data('pid');