簡體   English   中英

如何用JavaScript替換空的html標簽?

[英]How to replace empty html tags with javascript?

我有一些代碼想要插入或替換為所需的代碼集(如果為空)。 Javascript或jQuery有什么方向嗎?

如果html代碼等於:

<td id="Display1234"></td>

改成:

<td id="Display1234">
    <select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style="">
      <option value="101" selected="">Free</option>
    </select>
</td>

您首先需要獲取頁面上的所有元素(因為我假設您不知道哪些元素為空)。

// need to use Array.prototype.slice because getElementsByTagName
// returns an HTMLCollection and not an Array
var allElementsArray = Array.prototype.slice.call(document.body.getElementsByTagName('*'));

var emptyElements = allElementsArray.filter(function(element) {
  return !element.innerHTML; // returns true for all empty elements
});

我不知道要插入什么數據,但是您可以循環遍歷emptyElements數組;

emptyElements.forEach(function(element) {
  element.innerHTML = 'some content or HTML';
});

嘗試將以下內容用於純JavaScript解決方案:

 var td = document.getElementById('Display1234'); if (td.innerHTML.trim() == ""){ // Creating the select element var select = document.createElement('select'); select.setAttribute('name', 'ShippingSpeedChoice'); select.setAttribute('onchange', 'RecalcShipping(this);'); select.setAttribute('style', ''); // Creating the option element var option = document.createElement('option'); option.innerText = "Free"; option.setAttribute('value', '101'); option.setAttribute('selected', ''); // Appending elements to td element select.appendChild(option); td.appendChild(select); } 
 <table> <td id="Display1234"></td> </table> 

$('#Display1234').html('your html');
// if the div is empty
if($("#Display1234").html()===""){
    // create a a <select> element
    var $sel = $('<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style="">');
    // add an option to the select element
    $sel.append('<option value="101" selected="">Free</option>');
    // add the select element to the div.
    $sel.appendTo("#Display1234");
}

 window.addEventListener("DOMContentLoaded", function(){ var theCell = document.getElementById("Display1234"); if(theCell.textContent.trim() === ""){ theCell.innerHTML = '<select name="ShippingSpeedChoice" onchange="RecalcShipping(this);" style=""> <option value="101" selected="">Free</option></select>' } }); 
 <table> <tr> <td id="Display1234"></td> <td id="other1">something</td> <td id="other2">something else</td> </tr> </table> 

暫無
暫無

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

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