【问题标题】:Load content from website into an attribute将网站内容加载到属性中
【发布时间】:2013-08-17 11:46:09
【问题描述】:

我需要将链接 (#product_buy) 的 href 更新为可以在 #product_buy_source div 内的另一个页面上找到的 URL。这是 jQuery。

$('body').ready(function(){

    $('#product_buy').attr('href', function(){
        $(this).load('http://cdn.jeremyblaze.com/theme_info.html #Altitude .product_buy_source');
    });

});

这是需要编辑的链接。

<a href="#" id="product_buy">Purchase</a>

我感觉我使用的 jQuery 是完全错误的。有没有人能让它工作?这里有一点fiddle

【问题讨论】:

  • 你是否设置了另一端的文件允许跨域请求?
  • @Juhana 它在我的域中,所以它应该没关系吗?
  • 除非此文件也在 cdn.jeremyblaze.com 上,否则它确实很重要。子域也必须匹配。
  • @Juhana 你能告诉我一个关于如何做到这一点的教程吗?但是我能够成功地将简单的内容加载到 div,所以我认为它确实工作。
  • 我不知道你想做什么。为什么加载字符串中有两个 id?

标签: jquery href attr


【解决方案1】:

.load() 将数据加载为调用它的元素的HTML。要使用.load()(以便您可以指定一个选择器)来设置href,您需要类似:

// load it into a temp element, and assign the href once it is loaded
$('<div/>').load('http://cdn.jeremyblaze.com/theme_info.html #Altitude .product_buy_source', function() {
    $('#product_buy').attr('href', $(this).text());
});

或者,以更直接的方式,例如:

$.get('http://cdn.jeremyblaze.com/theme_info.html', function(data) {
    $('#product_buy').attr('href', $(data).find('#Altitude .product_buy_source').text());
});

【讨论】:

  • 第二个几乎可以了!问题是它只是将[object%20Object] 添加到当前页面URL 的末尾。有什么建议吗?
  • @JeremyBlazé - 我忘记了最后的 .text() 位。即$(data).find('#Altitude .product_buy_source'').text() - 检查修改后的答案。
  • 又一次非常接近,但现在似乎只是刷新页面。
  • 别担心,我得到了第一个完美的工作!感谢您的所有帮助!
猜你喜欢
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-04
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
  • 2013-04-02
相关资源
最近更新 更多