【问题标题】:Replace returned data from a jQuery ajax call before show it在显示之前替换从 jQuery ajax 调用返回的数据
【发布时间】:2012-10-29 23:47:56
【问题描述】:

这应该很简单,但我在这个问题上疯了。基本上我想要做的是在页面上显示之前从返回的 HTML 数据中替换一些标签。例如:

$.ajax({
    url: url,
    cache: false,
    type: 'GET',
    success: function(data) {
        // Here i need to replace href in ALL <a> tags and add the onclick attrib with the contents from the href 
        $('#floaty-dialog').html(modifieddata);
    }
});

如何预处理 HTML 数据并将所有 href 属性替换为 # 并将 onclick 属性添加到相同的链接??

【问题讨论】:

  • 像修改其他 dom 元素一样修改它。 var modifieddata = $(data); modifieddata.find('a').each(function(){...})

标签: jquery html ajax parsing replace


【解决方案1】:

我会使用浏览器的 HTML 解析器为我完成这项工作:

var dom = $(data);
dom.find("a").each(function() {
  var href = this.href;
  $(this).click(function(e) {
    e.preventDefault();
    alert(href);
  });
}).attr("href", "#");

$('#floaty-dialog').html(dom);

【讨论】:

  • 我现在已经接受了,几分钟前我读到我应该等待 7 分钟才能接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2010-10-27
相关资源
最近更新 更多