英文:
How can I export dynamically added event listeners to a static HTML file?
问题
所以我正在构建一个网站创建器。用户可以拖拽<div>
元素在页面上,并为这些<div>
元素添加onClick
事件监听器。我希望用户能够"发布"网站,将所有<div>
元素保存在一个HTML文件中,并保留它们的onClick
事件监听器。
为了"导出"用户的网站,我调用了jQuery的.html()
函数:
$('#builder').html()
这个函数包含了所有<div>
元素的HTML内容,但没有包含事件监听器 :(。
正如您在这里所见,点击监听器附加在img
元素上,但HTML中没有设置onclick
属性。
是否有一种方法可以修改HTML标签本身的onclick
属性?我只想在静态HTML文件中保留事件监听器。
英文:
So I'm building a website creator. Users can add drag divs around a page and add onClick event listeners to these divs. I would like the user to be able to 'publish' the website, which will save all the <divs> in an html file along with their onClick event listeners.
To "export" the user's website, I called the jquery .html()
function:
$('#builder').html()
Which contains all the html of all the divs, but none of the event listeners :(.
As you can see here, the click listener is attached to the img, but the 'onclick' attribute is not set in the HTML.
Is there a way to modify the onclick
attribute in the HTML tag itself? I just want to preserve event listeners in a static HTML file.
答案1
得分: 1
Here is the translated content:
"由于您标记了jQuery,这里是jQuery的解决方案。您可以使用 attr 来设置任何HTML属性。
$(element).attr('onclick', '您的神奇代码');
祝好运!
英文:
Since you tagged jQuery, here is the jQuery solution. You can use attr to set any HTML attribute.
$(element).attr('onclick', 'your magical code');
Cheers!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论