2014-11-02 36 views
2

我需要獲取帶有動態生成的ID的div的'角色'屬性。獲取帶動態ID的點擊div的屬性

HTML:

<div id="renable0" role="0"> 
    false 
</div> 
<div id="renable1" role="1"> 
    true 
</div> 
<!-- THE LIST OF DIVS CONTINUES IN INCREASING INCREMENTS OF 1 --> 

的Javascript:

$("[id^='renable']").editInPlace({ // editInPlace is a jQuery plugin 
    url: 'save.php', 
    params: 'pos='+$(this).attr('role') // How can I get this role attribute for the clicked div? 
}); 

回答

3

你需要使用.each()循環:

$("[id^='renable']").each(function() { 
    $(this).editInPlace({ 
     url: 'save.php', 
     params: 'pos='+$(this).attr('role') 
    }); 
}); 

如果editInPlace允許params選項是一個函數,就像其他一些jQuery插件爲類似選項所做的那樣,這將是很好的選擇。但既然沒有,你需要這樣做。

順便說一下,您對role屬性的使用與其作爲ARIA的一部分打算使用的方式不符。標準角色是buttonmenuitem之類的東西。你不應該濫用像這樣的標準屬性,或者組成自定義屬性。如果您想在元素中添加額外的屬性,請使用data-XXX元素。

<div id="renable0" data-role="0"> 

你可以在jQuery中用$(this).data('role')來訪問它。

0

this不會參考,以你的元素,你應該保持對它的引用:

// loop through your elements 
$("[id^='renable']").each(function() { 
    // keep reference to it 
    var $elem = $(this); 

    // make it editInplace 
    $elem.editInPlace({ 
     url: 'save.php', 
     params: 'pos='+$elem.attr('role') 
    }); 
});