0 秒 javascript 替换

0 sec javascript replace

我有一个看起来像这样的代码。 它基本上用图像替换“'php echo'”。 但是...当我加载或重新加载页面时,我仍然可以看到“'php echo'”我希望在 0 秒内直接加载该图像,所以我不需要看到“'php echo'”并加载它0 秒内的图像。 /// 抱歉我的英语不好。

视频示例:https://youtu.be/XFI7DIrlVcM

<td id="X"><?php echo $row['11']; ?></td>

<script>
var tdList = document.getElementsByTagName('td');
for(var i=0; i< tdList.length; i++){ 
  if(parseInt(tdList[i].innerHTML.trim())>= 0 && parseInt(tdList[i].innerHTML.trim())< 10 && tdList[i].getAttribute('id') == "X")
  tdList[i].innerHTML = '<img src="http://i.imgur.com/bgwZcHq.png">'
}
</script>

然后从 td 的内容中删除该值并将其作为 data attribute, which you can then retrieve in JavaScript with the dataset [=25] 放在 td 上=].

<!-- Put the empty <img> element into the cell so that the DOM is built correct from the start -->
<td id="X" data-value="<?php echo $row['11']; ?>"><img id="replace" title=""></td>

<script>

// Get all the td elements in an array
var tdList = Array.prototype.slice.call(document.querySelectorAll("td"));

// Get a reference to the empty image element
var img = document.getElementById("replace");

// Loop over the array
tdList.forEach(function(td){
  var val = parseInt(td.dataset.value, 10);
  
  // Check the id first for better performance since we don't care 
  // about the value unless we have the right element:
  if(td.id === "X" && val >=0 && val < 10 ){
    // Now, we only have to update the image element, not rebuild the DOM
    replace.src = "http://i.imgur.com/bgwZcHq.png";
  }
});

</script>

页面上没有呈现 <td>,因为 <td> 仅在非常特定的上下文中有效:在 <table><tr> 中,这就是为什么您的 <td> 根本没有被接收的原因。

如果将 <td> 更改为 <span> 和 运行 相同的代码,您将获得预期的结果:

var tdList = document.getElementsByTagName('span');
for(var i=0; i< tdList.length; i++){ 
  if(parseInt(tdList[i].innerHTML.trim())>= 0 && parseInt(tdList[i].innerHTML.trim())< 10 && tdList[i].getAttribute('id') == "X")
  tdList[i].innerHTML = '<img src="http://i.imgur.com/bgwZcHq.png" />'
}
<span id="X">1</span>