This (simple) code seems to give me nightmares.
这个(简单的)代码似乎让我做噩梦。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-source="ryedai">Ryedai</a>
<a href="#" data-source="alcea">Alcea</a>
<div class="formClass">
<div id="editor"></div>
</div>
<script>
$(document).ready(function() {
$('a[data-source]').on('click', function(e) {
e.preventDefault();
var source = $(this).data('source');
myeditFunction(source);
});
function myeditFunction(source) {
if (source === 'ryedai') {
$("#editor").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/social_media_-_mastodon_ryedai-mastodon.social.html");
} else if (source === 'alcea') {
$("#editor").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/social_media_-_mastodon_alcea-pbtodon.de.html");
}
}
});
</script>
I can click any of the link(s) and it will load the element into the dom no problem.
But the second time, it is raining "Syntax error - variable already declared" errors in the console.
我可以点击任何链接(S),它会毫不费力地将元素加载到DOM中。但是第二次,它在控制台中出现了“语法错误-变量已声明”错误。
How do I fix this ?
我该怎么解决这个问题?
I don't understand why I cannot rewrite the element like this
我不明白为什么我不能这样重写元素
更多回答
Is there a script in the page you are loading?
您要加载的页面中是否有脚本?
I suppose, but if that were an issue, then that'd hinder the initial load also.. However that is a good suggestion. Edit: both the htmls actually do have a apiUrl. But isn't that constricted to the html each their own ?
我想是的,但如果这是个问题,那也会阻碍最初的负荷..然而,这是一个很好的建议。编辑:这两个htmls实际上都有一个apiUrl。但这不是限制在各自的html上吗?
优秀答案推荐
The HTML document at https://alcea-wisteria.de/PHP/social_media_-_mastodon_ryedai-mastodon.social.html
contains a <script>
element.
Https://alcea-wisteria.de/PHP/social_media_-_mastodon_ryedai-mastodon.social.html上的Html文档包含一个<脚本>元素。
That script declares a global const
variable.
该脚本声明了一个全局常量变量。
When you load
the HTML document, that script is executed and creates that variable.
当您加载HTML文档时,该脚本将被执行并创建该变量。
When you load
it again, the script is executed again, and throws an error when it tries to recreate that constant.
当您再次加载它时,脚本将再次执行,并在尝试重新创建该常量时抛出错误。
As a couple of rules of thumb:
以下是几条经验法则:
- Avoid using
load
to pull in entire HTML documents with their own scripts which pollute the DOM. Instead load minimum amounts of pure content (perhaps as HTML with load
or perhaps as JSON which you then create a DOM from) and use delegation for interactivity.
- Avoid using global variables. The simplest way to avoid them is to write your code as modules where the top level scope is the module instead of global.
更多回答
can you give an example of such "module" ? I want to really avoid constant variables. But I wasn't sure how. Thanks.
你能举一个这样的“模块”的例子吗?我想要真正避免恒定的变量。但我不确定是怎么回事。谢谢。
Perfect ! This helps :)
太好了!这有助于:)
我是一名优秀的程序员,十分优秀!