我的页面上有一个叫做"a.add_mycrate“的重复类。这个脚本只针对点击的实例(这个),并处理它。
这是我的JS:
jQuery(document).ready(function(){
jQuery(document).on('click', "a.add_mycrate", function(event) {
event.preventDefault();
var title = jQuery(this).attr('data-title');
var artwork = jQuery(this).attr('data-artwork');
var stream = jQuery(this).attr('data-stream');
var download = jQuery(this).attr('data-download');
var data = {
'action': 'addToCrate',
'security': jQuery( '#crate-nonce' ).val(),
'podtitle' : title,
'podartwork' : artwork,
'podstream' : stream,
'podsave' : download
};
jQuery.post(myCrate.ajaxurl, data, function(response) {
jQuery('a.add_mycrate', this).html(response);
alert(response);
});
});
});这是在页面上呈现实际链接的方式(以防有帮助):
<a class="add_mycrate" href="#" data-title="Title Goes Here" data-artwork="artwork.jpg" data-stream="myfile.mp3" data-download="link/to/download">Add To Crate</a>当获取vars的数据时,(这个)选择器工作得很好,但是我无法在响应"a.add_mycrate“的目标(这个)实例中获得代码。这是我遇到麻烦的台词:
jQuery('a.add_mycrate', this).html(response);我知道我一定是做错了,但我在这里四处看看的所有尝试都没有用。有什么建议吗?
不相关的问题,但我使用的是"jQuery“而不是"$”,因为它是运行在一个wordpress网站上,以防有人怀疑。
发布于 2016-01-24 15:51:21
若干问题:
this内部的$.post回调不是您所认为的那样。在外部事件处理程序中,它的作用域上下文与this不同。在ajax之外存储对this的引用,以便在其中使用
var $this = jQuery(this);
jQuery.post(myCrate.ajaxurl, data, function(response) {
$this.html(response);
});这也将解决以下方面的问题:
jQuery('a.add_mycrate', this).html(response);第二个论点是“语境”。如果假设this是元素,则上下文参数使其与以下内容相同:
jQuery(this).find('a.add_mycrate');所以你会在里面寻找元素。通过将元素引用存储在ajax之外并将html直接插入到存储的元素中,解决了这两个问题。
编辑:如何在wordpress noConflict()中使用$而不必对所有内容使用jQuery:
jQuery(document).ready(function($){
// can use `$` for all your code inside the ready handler
// when you pass it in as argument
})发布于 2016-01-24 15:52:11
将this放在一个名为elm的变量中,在post之前,然后更改elm的html,如下所示。
jQuery(document).ready(function(){
jQuery(document).on('click', "a.add_mycrate", function(event) {
event.preventDefault();
var title = jQuery(this).attr('data-title');
var artwork = jQuery(this).attr('data-artwork');
var stream = jQuery(this).attr('data-stream');
var download = jQuery(this).attr('data-download');
var elm = this;
var data = {
'action': 'addToCrate',
'security': jQuery( '#crate-nonce' ).val(),
'podtitle' : title,
'podartwork' : artwork,
'podstream' : stream,
'podsave' : download
};
jQuery.post(myCrate.ajaxurl, data, function(response) {
jQuery(elm).html(response);
alert(response);
});
});
});https://stackoverflow.com/questions/34977725
复制相似问题