将onclick添加到动态创建的span标记中



这似乎是一件微不足道的事情,但由于某种原因,我无法使其工作。

我正在尝试使用execCommand高亮显示contenteditablediv标记中的文本。但是,我不能使用"hiliteColor"参数,因为我还想在span标记中添加一个onclick事件(以便能够再次删除高亮显示(。下面是这个函数的样子:

export function highlight(color){
//remove any format to avoid overlap issues
document.execCommand('removeFormat', false, null);
//save selected text
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
//create new span around the text
var span = document.createElement("span");
span.style.backgroundColor = color;
span.onclick = doSomething();  // <-------------------------------- ISSUE
span.innerText = text;
document.execCommand('insertHTML', false, span.outerHTML);
}
function doSomething(){
alert('I was clicked!');
}

我尝试通过多种方式添加函数,包括span.addEventListener('click', () => alert('test'));,但onclick从未添加到span标记中。在上面一行添加样式效果很好。

如果这很重要的话,我会在React应用程序中执行此操作。

如何将函数附加到此跨度?还是有一种完全不同的方式来突出显示?

谢谢。

如果使用React,我建议使用React创建元素,使用ReactDOM渲染元素。你可以像一样在你的组件中导入ReactDOM

import ReactDOM from "react-dom";

然后您可以创建并呈现元素

let SpanElement =  React.createElement(
"span",
{
style: { backgroundColor: "#0099FF"}, //Color Here
id: "SpanID",
className: "SpanClassName",
onClick: () => doSomething()
},text);

// First Argument element to Render, Second Argument: Node to Render at
ReactDOM.render(SpanElement, document.getElementById("root")); 

我怀疑span标记中的文本是空字符串

// CASE 1
let hasText = document.createElement("span")
hasText.innerText = "I am span element"
hasText.onclick = () => console.log("clicked - text")
hasText.style.background = `red`
document.body.appendChild(hasText)
// CASE 2
let noText = document.createElement("span")
noText.onclick = () => console.log("clicked - no text")
noText.style.border = `green`
document.body.appendChild(noText)

最新更新