簡體   English   中英

jQuery動態更改html內容

[英]JQuery change html content dynamically

我有一個右側欄,可以滑出並顯示內容。 可以從多個按鈕(button1,button2,button3等)打開側欄。單擊某些按鈕時,側欄中的內容是否需要不同? 最有效的方法是什么? 我嘗試使用.html(),但它會覆蓋樣式。 例如,如果button1觸發的內容為“ Test”,而button2顯示為“ Test2”,則再次單擊button1時,它將顯示為“ Test2”。 有沒有一種方法可以有效地維護每個點擊事件的數據一致性?

試試這個代碼:

 $("input").click(function() { var value = this.getAttribute('data-dynamicContent'); document.getElementById('dynamicContent').innerHTML = value; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" data-dynamicContent="This is your content" value="button one"> <input type="button" data-dynamicContent="This is your content 2" value="button two"> <input type="button" data-dynamicContent="This is your content 3" value="button three"> <div id="dynamicContent"></div> 

這是一種不太干凈的瀏覽器,但提供更好的瀏覽器支持:

 $('input').click(function() { document.getElementById('dynamicContent').innerHTML = this.name; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" name="your content one" value="button one"> <input type="button" name="your content two" value="button two"> <input type="button" name="your content three" value="button three"> <div id="dynamicContent"></div> 

這是具有更多代碼但具有最佳瀏覽器支持的代碼:

 $('input').click(function() { document.getElementById('dynamicContent').innerHTML = this.nextElementSibling.value; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input type="button" value="button one"> <input type="hidden" value="your content one"> </div> <div> <input type="button" value="button two"> <input type="hidden" value="your content two"> </div> <div> <input type="button" value="button two"> <input type="hidden" value="your content three"> </div> <div id="dynamicContent"></div> 

暫無
暫無

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

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