Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery$(this)不会将文本插入到我的元素中_Javascript_Jquery_Html - Fatal编程技术网

Javascript jQuery$(this)不会将文本插入到我的元素中

Javascript jQuery$(this)不会将文本插入到我的元素中,javascript,jquery,html,Javascript,Jquery,Html,我目前正在为我的一个项目添加标记功能,但我无法让jQuery的$(this)选择器工作 这样做的目的是在用户单击div时,将flag中的文本更改为flagged,ajax查询将成功运行。我的HTML/PHP是: <div class="flag" post_to_flag='".$post_to_flag."'>Flag</div> 我无法将文本替换为标记的,但是如果我将此选择器替换为标记选择器,它将用页面上的标记类替换所有内容 我已经检查过了,$(this)选择器很好

我目前正在为我的一个项目添加标记功能,但我无法让jQuery的
$(this)
选择器工作

这样做的目的是在用户单击
div
时,将
flag
中的文本更改为
flagged
,ajax查询将成功运行。我的HTML/PHP是:

<div class="flag" post_to_flag='".$post_to_flag."'>Flag</div>
我无法将文本替换为标记的
,但是如果我将
选择器替换为
标记
选择器,它将用页面上的标记类替换所有内容


我已经检查过了,
$(this)
选择器很好地获得了“post\u to\u flag”属性。为什么会发生这种情况,我如何修复它?

您应该添加一个上下文变量:

$('.flag').live('click', function () {
    var $context = $(this);
    $.post('../php/core.inc.php', {
        action: 'flag',
        post_to_flag: $context.attr('post_to_flag')
    }, function (flag_return) {
        if (flag_return == 'query_success') {
            $context.text('flagged');
        } else {
            alert(flag_return);
        }
    });
});
您正在
jQuery
选择调用中调用多个函数。当您进入
$.post()
函数时,您的作用域会发生变化
现在指的是与您在
one()
中时不同的作用域


@Moak的建议是,如果您将变量设置为jQuery对象,那么最好用开头表示变量
$
,以便于将来的读者或您自己了解。

ajax回调中的这个
不是元素,而是ajax对象本身

您可以使用
$.proxy
在上下文中传递


我还建议在变量前面加上
$
,例如
$context
$this
,以指示该值是jQueryobject@Moak对您当然可以这样做,这将有助于澄清它是一个jQuery对象。我来换一下。
$('.flag').live('click', function () {
    var $context = $(this);
    $.post('../php/core.inc.php', {
        action: 'flag',
        post_to_flag: $context.attr('post_to_flag')
    }, function (flag_return) {
        if (flag_return == 'query_success') {
            $context.text('flagged');
        } else {
            alert(flag_return);
        }
    });
});
$('.flag').live('click', function () {
$.post('../php/core.inc.php', 
      {action: 'flag', post_to_flag: $(this).attr('post_to_flag')},    
    $.proxy(function(flag_return) {
       if(flag_return == 'query_success'){
         $(this).text('flagged'); //Now this here will represent .flag
       }else{
         alert(flag_return);
       }
    },this)); //Now here you are passing in the context of `.flag`