【问题标题】:jQuery append is not working when using load before之前使用加载时jQuery追加不起作用
【发布时间】:2014-02-27 16:56:16
【问题描述】:

在加载函数后使用附加函数时不起作用。

$('section article a').on('click',function(e){

    e.preventDefault();
    id = $(this).attr('class');
    $('article[id='+id+']').load( 'articles/'+id+'.html' );

    $('article[id='+id+']').append( "<strong> Where am I?<br/>StackOverflow HELP !!!</strong>" );   //This is NOT appended

});

有什么想法吗?

【问题讨论】:

  • append 可能会在 load() 完成之前被调用。尝试将 load 与调用 append 的回调函数一起使用。加载(网址,[数据],[回调])api.jquery.com/load
  • 建议:不要使用 class 属性,而是使用 data- 属性。像 data-articleid 一样设置您的链接文章 ID。这将保护您应该在链接中添加 css 类。此外,由于 id 是唯一的,您可以只使用 $('#'+id) 选择器,甚至可以使用 $('article#'+id) 来让您感觉更安全。

标签: javascript jquery load append preventdefault


【解决方案1】:

尝试等到您的load 完成,然后改用append()

$('article[id='+id+']').load( 'articles/'+id+'.html', function() {
    $('article[id='+id+']').append( "<strong> Where am I?<br/>StackOverflow HELP !!!</strong>" ); 
});

您也可以只使用$('#'+id) 而不是$('article[id='+id+']'),因为id 是唯一的。

【讨论】:

  • 我需要等待 11 分钟才能接受您的回答,但已接受!完美!
  • 谢谢!很高兴它有帮助:D
  • +1 你也可以在加载回调中使用$(this).append(),因为范围没有变化;)
  • 谢谢阿切尔!很棒的提示!
猜你喜欢
  • 2010-11-03
  • 2011-11-10
  • 2014-04-15
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多