简体   繁体   English

访问DOM元素属性以设置全局变量

[英]Accessing a DOM element attribute to set a global variable

I'm using CKEditor and I'm setting the editor's base path by setting the global variable named CKEDITOR_BASEPATH like this: 我正在使用CKEditor,并且通过设置名为CKEDITOR_BASEPATH的全局变量来设置编辑器的基本路径,如下所示:

var CKEDITOR_BASEPATH = $('#ckeditor').data('basepath');

Now my question is, is it safe to access the data dash attribute of a DOM element this way? 现在我的问题是,以这种方式访问​​DOM元素的数据破折号属性是否安全? I'm doing it like this because I'm trying to avoid hard coding my URL in my script file and I can't really put this inside the jquery ready function as CKEditor requires that it should be a global variable. 我这样做是因为我试图避免在脚本文件中对URL进行硬编码,并且由于CKEditor要求它应该是一个全局变量,所以我不能真正将其放入jquery ready函数中。 It's working right now in my local but I'm not sure if this can cause an issue later. 现在在我的本地计算机上可以正常使用,但是我不确定这以后是否会引起问题。

Your approach is risky because it assumes that: 您的方法存在风险,因为它假设:

  1. jQuery is already loaded. jQuery已经加载。
  2. Element of id="ckeditor" has already been parsed. id="ckeditor"元素已被解析。
  3. CKEditor hasn't use the CKEDITOR_BASEPATH variable yet. CKEditor尚未使用CKEDITOR_BASEPATH变量。

Lots of constraints. 很多约束。 Different browsers may do different things here. 不同的浏览器在这里可能做不同的事情。 It's hard to tell because you didn't provide any information about how scripts are loaded (static or dynamically?) and what is the order . 这很难说,因为你没有提供有关脚本如何加载(静态或动态?)任何信息,什么是秩序 Still, the solution, as I guess is very simple because your code suggests that the element looks like: 我认为解决方案仍然非常简单,因为您的代码表明该元素看起来像:

<element id="ckeditor" data-basepath="there/is/your/path" />

...and since it is rendered in the template more or less like the following (let's assume PHP): ...并且由于其在模板中的呈现方式大致如下所示(我们假设使用PHP):

<element id="ckeditor" data-basepath="<?php echo $path ?>" />

...why don't you render the correct <script> tag on the top of the template (in <head> ) instead? ...为什么不在模板顶部(在<head> )呈现正确的<script>标签?

<script type="text/javascript">
    var CKEDITOR_BASEPATH = '<?php echo $path ?>';
</script>

...and the problem is solved. ...问题就解决了。

I'm doing it like this because I'm trying to avoid hard coding my URL 我这样做是因为我试图避免对URL进行硬编码

Nothing is hardcoded with this approach. 用这种方法没有硬编码。 No problems with the order of things. 事物顺序没有问题。 No more worries about DOM. 不用担心DOM。

PS : The problem you have is described in the official developers guide . PS :您遇到的问题在官方开发人员指南中有所描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM