[英]Replace the text of a <li> with image
How can i replace the text of a <li>
with an image when an event is called? 调用事件时,如何用图像替换<li>
的文本? When the <li>
is clicked i want to come an image at this place. 单击<li>
,我要在此位置显示图像。 I tried with innerHTML
but no result. 我尝试使用innerHTML
但没有结果。 Any idea? 任何想法?
<ul onclick="myFunction(event)">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
function myFunction(event){
var t;
if(event.target){
t = event.target;
}else{
t = event.srcElement;
}
t.innerHTML = '<img src="img.png">';
}
Let's say you have a structure like this: 假设您有一个这样的结构:
<ul>
<li>Some Text</li>
</ul>
You can use the following script as an event listener function: 您可以将以下脚本用作事件侦听器功能:
document.querySelector("li").addEventListener("click", function(event) {
let image = document.createElement("IMG");
image.src = "//placehold.it/20"; // example image
this.innerText = ""; // remove text
this.append(image); // append image to the li
});
This code in action: 该代码的作用:
document.querySelector("li").addEventListener("click", function(event) { let image = document.createElement("IMG"); image.src = "//placehold.it/20"; // example image this.innerText = ""; // remove text this.append(image); // append image to the li });
<ul><li>Some Text</li></ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.