2016-11-23 49 views
4

我有一個使用jQuery的網頁。在這個應用程序中,我有一個接受HTML字符串的函數。這個HTML字符串是動態生成的。但是,我知道我想更新HTML中某個元素的類列表。 HTML字符串的一個例子是這樣的:jQuery - 更新字符串的HTML

<p>This is a test</p><div class="example" data-id="1">example</div> <p>This is only a test.</p> 

我想找到這個字符串值的特定數據ID中的元素,並更新其類列表。在努力孤立我的問題,我已經創造了這個Fiddle,其中包括下面的代碼:

function updateHtml(html, id) { 
    var tree = $(html); 
    var updatedHtml = html; 

    var leaf = $(tree).find('div[data-id="' + id + '"]'); 
    if (leaf) { 
    $(leaf).attr('class', 'example complete'); 
    updatedHtml = $(tree).html(); 
    } 

    return updatedHtml; 
} 

當您運行的小提琴,你會發現,這些類不會真正改變。爲什麼不?我不知道我做錯了什麼。基於上面的代碼,小提琴中的例子從未像我期望的那樣從灰色變爲綠色。我錯過了什麼?

+0

你拍的HTML作爲一個字符串,然後你要更新該字符串,爲什麼會在頁面上的元素通過你做一個隨機字符串什麼影響?該函數也不返回任何東西。 – adeneo

+0

@adeneo公平評估。我着急了。我更新了小提琴和問題文本。 – user687554

+0

您是否真的需要HTML作爲字符串,爲什麼不直接添加類,如果您想要影響DOM呢? – adeneo

回答

1

您不需要更新html。你可以像下面這樣添加類。

function updateClass() { 
 
    var $elm = $('#myElement'); 
 
    updateHtml($elm, 1) 
 
} 
 

 
function updateHtml($elm, id) { 
 
    var leaf = $elm.find('div[data-id="' + id + '"]'); 
 
    if (leaf) { 
 
     $(leaf).addClass('example complete'); 
 
    } 
 
}
.example { 
 
    background-color:lightgray; 
 
    border: solid 2px #000; 
 
    padding:12px; 
 
} 
 

 
.complete { 
 
    background-color:green; 
 
    color:#fff; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div id="myElement"> 
 
     <p>This is a test</p> 
 
     <div class="example" data-id="1">example</div>  
 
     <p>This is only a test.</p> 
 
    </div> 
 
    <br /> 
 

 
    <button class="btn btn-primary" onclick="updateClass()"> 
 
     Run 
 
    </button> 
 
</div>

0
function updateHtml(html, id) { 
    $('div[data-id="' + id + '"]').addClass("complete").html(html); 
} 
0

我檢查你的例子在小提琴並提出以下更新,你可以試試下面的代碼,它應該工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <div id="myElement"> 
 
    <p>This is a test</p><div class="example" data-id="1">example</div> <p>This is only a test.</p> 
 
    </div> 
 
    <br /> 
 

 
    <button class="btn btn-primary" onclick="return updateClass();"> 
 
    Run 
 
    </button> 
 
</div> 
 
<script> 
 
function updateClass() { 
 
    var html = $('#myElement').html(); 
 
    
 
    var newHtml = updateHtml(html, '1'); 
 
    $('#myElement').html(newHtml); 
 
} 
 

 
function updateHtml(html, id) { 
 
    
 
    var updatedHtml = html; 
 
    var $html = $('<div />',{html:html}); 
 
    $html.find('div[data-id="' + id+'"]').addClass("example complet"); 
 
    
 
    return $html; 
 
} 
 
</script>