jquery html()删除脚本标签

前端之家收集整理的这篇文章主要介绍了jquery html()删除脚本标签前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要替换我的页面中的div的内容与ajax调用的html结果。
问题是,html有一些必要的脚本,它似乎jquery html()函数将其打包出来,
我需要过滤响应,只得到一个特定的div。

我想一个解决方法是从ajax响应中提取所有的脚本标签,然后附加他们做DOM,但我有麻烦这样做。

这里是我的代码;

  1. $('a.link-vote').live('click',function(){
  2. var idFeedback = $(this).attr('id').split('-')[1];
  3. var href = $(this).attr('href');
  4. $('.Feedback-' + idFeedback + '-loader').show();
  5. $.ajax({
  6. type: "POST",url: href,success: function(response){
  7. var x = $(response).find('#Feedback-'+ idFeedback).html();
  8. $('.Feedback-' + idFeedback + '-loader').hide();
  9. $('#Feedback-'+ idFeedback).html(x);
  10.  
  11. }
  12. });
  13. return false;
  14. });

我发现这个老主题
http://www.jb51.cc/article/p-hybnjvib-bss.html

但是任何结论。我试过建议的解决方案,但没有一个工作。

编辑:
我似乎找到了一个解决方案,基于那个老主题,但它不漂亮;

  1. var dom = $(response);
  2. // var x = $(response).find('#Feedback-'+ idFeedback).html();
  3. $('.Feedback-' + idFeedback + '-loader').hide();
  4. //$('#Feedback-'+ idFeedback).html(x);
  5.  
  6. $('#Feedback-'+ idFeedback).html(dom.find('#Feedback-'+ idFeedback).html());
  7.  
  8. dom.filter('script').each(function(){
  9. var obj = $(this);
  10. $('#Feedback-'+ idFeedback + ' .Feedback-comments').append(obj);
  11. });

必须有一个简单的方法

解决方法

编辑:我累了,不想。您只需使用原生innerHTML方法,而不是.html():
  1. $('#Feedback-' + idFeedback)[0].innerHTML = x;

原始答案:

我的预感是,你链接的答案不适合你,因为包括的脚本调用src属性,而不是脚本内容之间的< script>和< / script>标签。这可能工作:

  1. $.ajax({
  2. url: 'example.html',type: 'GET',success: function(data) {
  3.  
  4. var dom = $(data);
  5.  
  6. dom.filter('script').each(function(){
  7. if(this.src) {
  8. var script = document.createElement('script'),i,attrName,attrValue,attrs = this.attributes;
  9. for(i = 0; i < attrs.length; i++) {
  10. attrName = attrs[i].name;
  11. attrValue = attrs[i].value;
  12. script[attrName] = attrValue;
  13. }
  14. document.body.appendChild(script);
  15. } else {
  16. $.globalEval(this.text || this.textContent || this.innerHTML || '');
  17. }
  18. });
  19.  
  20. $('#mydiv').html(dom.find('#something').html());
  21.  
  22. }
  23. });

注意,这没有进行任何测试,可能会吃婴儿。

猜你在找的jQuery相关文章