簡體   English   中英

jQuery的同步DOM元素值

[英]jquery Syncing dom element values

我有一個像這樣的DOM元素:

<div id='master-value'>Apples</div>

我在頁面上的其他地方還有許多其他元素需要與“主值”同步。

<div class='fruit-value' data-reference='master-value'>Apples</div>
<div class='some-fruit' data-reference='master-value'>Apples</div>

更改“主值”的值時,我希望所有同步的元素都隨之更新。

$('#master-value').text('Pears');

應該影響:

<div class='fruit-value' data-reference='master-value'>Pears</div>
<div class='some-fruit' data-reference='master-value'>Pears</div>

我不希望每次更改“主值”時都必須搜索所有元素,以便找到已同步的元素以進行更改。 我認為當需要搜索許多元素時,這相當慢。

子值應預先綁定到主值,以便快速進行選擇。

$('.fruit-value, .some-fruit').sync('#master-value');

例如,我有一些想法:我可以創建一個預先選擇的同步對象數組,在主值上綁定一個自定義事件,並在我更改值時運行該事件。 該事件將通過數組更新所有子元素。

我敢肯定,這樣做有更好的方法...

謝謝!

您可以存儲一次選擇器,如下所示:

var elements = $('.fruit-value, .some-fruit'); //do this once

elements.text($("#master-value").text()); //when you want to sync

elements變量/ jQuery對象將保留對DOM元素的引用數組,因此不會每次遍歷都找到它們。

給他們全班上班難道不是很容易嗎?

所以你敢

$('.fruit').text('Pears')

如果您正在尋找功能性的插件類型,請嘗試以下操作:

設置時,它需要具有一個屬性syncWith的對象來設置應與之同步的元素。

設置文本時,它將為主要元素和同步元素設置文本。

試試看: http : //jsfiddle.net/GH33J/

只是第一次嘗試。 如果(例如)母版不止一個元素,則存在改進的空間。 應該有一個對所有要同步的元素的全局引用,並提供一個選項來告知是否也要同步主服務器

$.fn.sync = function(arg) {
       // if arg plain object, we are doing an initial setup
    if ($.isPlainObject(arg)) {
        return this.each(function() {
            $.data(this, 'syncWith', $(arg.syncWith));
        });
        // if arg is jQuery object, we are adding new items
    } else if (arg.jquery) {
        return this.each(function() {
            var $set = $.data(this, 'syncWith');
            $.each(arg, function() {
                $set.push(this);
            });
        });
        console.log(this.data('syncWith'));
        // otherwise assume we have a string, and are syncing a new value
    } else {
        return this.each(function() {
            $(this).text(arg);
            $.data(this, 'syncWith').text(arg);
        });
    }
};


// Set up the sync
$('#master-value').sync({
    syncWith: '.fruit-value,.some-fruit'
});

var $new = $('<div class="fruit-value">Apples</div>').appendTo('body');
// Pass a jQuery object containing newly created element(s) to add to the set
$('#master-value').sync($new);

// Activate a sync
$('#master-value').sync("pears");​

暫無
暫無

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

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