2013-05-27 23 views
35

属性をHTML data-select-content-valに作成しました。情報が動的に埋め込まれています。作成した属性の値の属性変更を検出しました

属性の値が変更されたときを検出する方法はありますか?

$(document).on("change", "div[data-select-content-val]", function(){ 
    alert("BOOP!"); 
}); 

答えて

38

DOMノードの変更を監視する必要があります。 MutationObserverというAPIがありますが、サポートが非常に限られているようです。このSO answerには、APIのstatusへのリンクがありますが、これまでのところIEやOperaでサポートされていないようです。

この問題を回避する方法の1つは、data-select-content-val属性を変更するコードの部分を聴くことができるイベントにすることです。

例えば、一緒につなぐ方法については、http://jsbin.com/arucuc/3/editを参照してください。

ここでのコードは、属性変更をするためにイベントリスナーを追加しますthisの拡張機能があります

$(function() { 
    // Here you register for the event and do whatever you need to do. 
    $(document).on('data-attribute-changed', function() { 
    var data = $('#contains-data').data('mydata'); 
    alert('Data changed to: ' + data); 
    }); 

    $('#button').click(function() { 
    $('#contains-data').data('mydata', 'foo'); 
    // Whenever you change the attribute you will user the .trigger 
    // method. The name of the event is arbitrary 
    $(document).trigger('data-attribute-changed'); 
    }); 

    $('#getbutton').click(function() { 
    var data = $('#contains-data').data('mydata'); 
    alert('Data is: ' + data); 
    }); 
}); 
+7

ので、あなたの答えは検出ではなく、ときにクリックでイベントをトリガしていないです待って? Hmmm – ChristoKiwi

+1

@ChristoKiwiこれは私には意味がありません。 – Jose

6

です。

使用方法:選択した要素

$(selector).attrchange({ 
    trackValues: true, /* Default to false, if set to true the event object is 
       updated with old and new value.*/ 
    callback: function (event) { 
     //event    - event object 
     //event.attributeName - Name of the attribute modified 
     //event.oldValue  - Previous value of the modified attribute 
     //event.newValue  - New value of the modified attribute 
     //Triggered when the selected elements attribute is added/updated/removed 
    }   
}); 
+0

FYI 2番目のスクリプトは「見つかりません」 – DrLightman

+0

このリンクは動作します:https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange .js –

+0

オブザーバーがサポートされていないため、このソリューションはFirefoxとEdgeをクラッシュさせます。 –

3

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> 
<script type="text/javascript" 
    src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script> 

バインドattrChangeはハンドラ関数あなたはdata-*変更を含む属性変更を追跡するためMutationObserverを使用することができます。たとえば:

var foo = document.getElementById('foo'); 
 

 
var observer = new MutationObserver(function(mutations) { 
 
    console.log('data-select-content-val changed'); 
 
}); 
 
observer.observe(foo, { 
 
    attributes: true, 
 
    attributeFilter: ['data-select-content-val'] }); 
 

 
foo.dataset.selectContentVal = 1;
<div id='foo'></div> 
 

関連する問題