jQuery:无法改变外部加载的内容

时间:2013-07-22 12:53:02

标签: jquery

问题:我们正在非常有限的CMS上建立一个网站。我们需要替换锚点href中的某个函数。不幸的是,加载的内容是外部的,这段代码不起作用:

jQuery的:

$(document).ready(function() {
    $('a[href*="show_upsell_dialog"]').each(function(e){
            $(this).attr('href', $(this).attr('href').replace('show_upsell_dialog(', 'more_details_1('));
    });   
});

HTML位:

<a href="javascript:show_upsell_dialog(1238)">Details</a>

问题:为什么?我如何使其发挥作用?

3 个答案:

答案 0 :(得分:1)

如果您无法访问$ .get或$ .get返回的承诺,则您的选项非常有限。

另一种方法是使用全局ajax回调,当调用具有预期选项的请求时,该回调将自行解除绑定。

function completeCallback (e, xhr, options) {
    // updated
    if (options.url == "/ejax-order-step/") {
        $(e.currentTarget).off('ajaxComplete',completeCallback);
        $('a[href*="show_upsell_dialog"]').attr('href',function(href){
            return href.replace('show_upsell_dialog(', 'more_details_1(');
        });
    }
}
$(document).ajaxComplete(completeCallback);

但请注意,此回调必须在其收听的请求完成之前定义。

在你的情况下,我不明白为什么你不能这样做:

window.show_upsell_dialog = window.more_details_1;

答案 1 :(得分:-1)

您可以尝试以下代码:

$(function() {
    $('a[href*="show_upsell_dialog"]').each(function(){
        $(this).attr('href', $(this).attr('href').replace('show_upsell_dialog', 'more_details_1'))
    });
})

答案 2 :(得分:-1)

为您的函数命名并在其中调用它 setTimeout(yourFuncName,1000);

如果1秒太短,请尝试2.我只是在猜测,但有时候setTimeout很有用......