2017-06-06 28 views
0

在我的項目我有一個表,它的每一個行持有的id和標題的數據屬性數據屬性沒有更新頁面刷新之前使用jQuery

<tr data-id="1" data-title="title"><td id="td_title">some text</td></tr> 

我使用jQuery來更新數據瓦屬性

$newTitle = 'newTitle'; 
$row_to_update = $("tr").find("[data-id='1']"); 
$row_to_update.attr('data-title', newTitle); 

所以在這之後,在HTML中,我可以看到更新後的值,但如果我試試這個:

$var = $row_to_update.data('title'); 
alert($var); 

它retur ns是舊的標題,除非我再次加載頁面。 我想我必須清除緩存,但我只找到$.domCache,這並不適用於jQuery和也看到了,並試圖

function clearjQueryCache(){ 
    for (var x in jQuery.cache){ 
     delete jQuery.cache[x]; 
    } 
} 

,但顯然不是正確的,因爲一切都停止了工作

回答

1

.find()方法允許我們搜索DOM樹中這些 元素的後代,並從 匹配元素構造一個新的jQuery對象。 .find()和.children()方法類似, 除了後者僅在DOM樹下傳送單個級別。

隨着$("tr").find("[data-id='1']");tr沒有元素與[data-id='1']找到它。所以沒有必要使用.find()

$newTitle = 'newTitle'; 
$row_to_update = $("tr[data-id='1']"); 
$row_to_update.data('title', $newTitle); 
//then 
$var = $row_to_update.data('title'); 
alert($var); // the output should be newTitle 

工作演示

$(document).ready(function(){ 
 
    $newTitle = 'newTitle'; 
 
    $row_to_update = $("tr[data-id='1']"); 
 
    $row_to_update.data('title', $newTitle); 
 
    //then 
 
    $var = $row_to_update.data('title'); 
 
    alert($var); // the output should be newTitle 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
<tr data-id="1" data-title="title"><td id="td_title">some text</td></tr> 
 
<tr data-id="2" data-title="title"><td id="td_title">some text</td></tr> 
 
</table>

+0

謝謝,儘管我可以清楚地看到你的代碼正在工作,即使我使用$(「tr [data-id ='1']」),alert()仍然顯示舊值。 – Dimentica

+0

@Dimentica是否改變了'.attr('data-title',newTitle);'用'.attr('data-title',$ newTitle);'..而CTRL + F5會刷新你的網站 –

+0

是的,我沒有,我可以在html中看到標題已更改,但是警告消息認爲其他情況 – Dimentica

0

相反比.data('title'),您可以使用.attr('data-title')。這可能工作。