簡體   English   中英

jQuery,頁面加載后加載元素

[英]JQuery, load elements after page loaded

我想做這樣的事情:

<img src="" class="after-all" data="/assets/huge-bg.png" />
<div class="after-all" data="/actions/div-content.html"></div>

而在JS中

$("after-all").loadMissing();

我認為最好的方法是使用識別方法構建一個插件:

if (img) $(this).attr('src', $(this).attr('data'));
if (div) $(this).load($(this).attr('data'));

這可能嗎 ? 做這個的最好方式是什么 ? 這個怎么做 ?

您可以使用is()

$.fn.loadMissing = function() {
    return this.each(function() {
        var $this = $(this);
        if ($this.is("img")) {
            $this.attr("src", $this.attr("data"));
        } else if ($this.is("div")) {
            $this.load($this.attr("data"));
        }
    });
};

請注意,您應該使用data以外的其他屬性來存儲此信息。 data-content這樣的HTML5數據屬性可能是一個更好的解決方案。

暫無
暫無

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

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