簡體   English   中英

在鏈接上單擊加載容器中的html頁面

[英]On link click load html page in container

jQuery新手在這里有一個快速的問題。 我在html中有兩個空容器:
<aside></aside>
<section></section>

然后將內容加載到其中:

$('aside').load('timeline.html #dates');
$('section').load('timeline.html #intro');

#dates包含的鏈接在單擊時應替換並將其url內容加載到<section>而不重新加載整個頁面。 我嘗試制作一個點擊處理程序,但是它不起作用(點擊仍然離開當前頁面並轉到url):

$('a').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    var url = $(this).attr("href");
    $('section').empty().load(url);  
});

我什至嘗試了這種變化,但沒有成功:

$('aside a').on('click', function() {
    var url = $(this).attr("href");
    $('section').empty().load(url);
    return false;
});

我可以使用iframe,但是由於我正在學習.load(),所以我不想這樣做。 有什么建議么?

也許使用ajax而不是load

JSFIDDLE: http : //jsfiddle.net/neuroflux/yHVMA/

$('aside a').on('click', function() {
    var url = $(this).attr("href");
    $.ajax({
        url: url,
        type: 'jsonp', //for x-domain
        success: function(data) {
            console.log(data);
            $("section").html(data);
        },
        error: function(err) {
            alert("bugger!\r\n" + data);
        }
    });
    return false;
});

嘗試這個:

$(document).on('click', 'aside a', function(e) {
    e.preventDefault();
    var url = $(this).attr("href");
    $('section').empty().load(url);
});

在您的情況下,如果動態加載錨,則事件可能未附加到錨

您正在加載內容之前注冊click()處理函數。 在加載內容之后,必須從load()complete處理程序中執行此操作:

function click_handler() {
    $(this).load($(this).attr("href"), {}, add_handlers)
    return false;
}

function add_handlers() {
    $(this).find('a').click(click_handler)
}

$('#box').load('/whatever/', {}, add_handlers)

請注意,加載新內​​容后,每次如何運行add_handlers() 請參見一個示例,當您單擊該鏈接時會重新加載該鏈接

您必須指定要加載頁面的部分的ID,然后將其加載到該section標記中。由於頁面中有很多部分

<section id="sec"></section>

然后是代碼

 $(document).ready(function(){
     $('a').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
         var url = $(this).attr("href");
       $('#sec').empty().load(url);  
    });
    });

感謝Karaxuna,Neuro,Sarath和其他人,這是我正在工作的代碼。 .load()保留了導致沖突的已加載頁面中的CSS,因此在鏈接單擊時,我只是隱藏了部分,而是將新頁面加載到了iframe中(沒有CSS沖突)。 為了確保我只針對某些元素,我在使用>選擇器,以便在圖片.load()時不針對重復的標簽。

<aside>
</aside>

<section>
</section>
<iframe class="no-display">
</iframe>   

<script>
 $(document).ready(function() {
    $('aside').load('timeline.html #dates');
    $('body > section').load('timeline.html #intro');
    $(document).on('click', 'aside a', function(e) {
        e.preventDefault();
        $('body > section').hide();
        $('iframe').removeClass('no-display');
        var url = $(this).attr('href');
        $('iframe').attr('src', (url));
    });
 });    
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM