jQuery如何从字符串中创建DOM元素



我正在尝试从字符串中创建一个元素,该元素是外部库(由bootcamp backamp by Bootcamp(所需的,以实现为VUE组件。因此,我在Trix问题中找到了以下片段:

let _ = require('lodash');
Vue.component('wysiwyg', {
  props: ['value'],
  template: '<div></div>',
  data() {
    return {
      trix: null,
      id: ''
    }
  },
  mounted() {
    this.id = _.sampleSize('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');
    this.trix = $(`<trix-editor input="${this.id}"></trix-editor>`);
    let self = this;
    this.trix.on('trix-change', (e) => {
      self.$emit('input', e.currentTarget.innerHTML)
    });
    this.$watch('value', function(value) {
      value = value === undefined ? '' : value;
      if (self.trix[0].innerHTML !== value) {
        self.trix[0].editor.loadHTML(value);
      }
    });
    this.trix.insertAfter(this.$el);
  },
});

他们使用jQuery创建元素,我想避免这种元素。使用模板标签或DOMParser,库不会加载 - 不过使用$(template),一切都可以顺利进行。
以下片段以及如何使事情正确之间有什么区别?

我尝试了几种失败的方法:

  1. createContextualFragment

    let el = document
         .createRange()
         .createContextualFragment('<div class="foo"></div>')
    
  2. 带有模板标签:

    let template = document.createElement('template');
    template.innerHTML = '<div class="foo"></div>';
    let el = template.content.firstChild;
    
  3. 使用DOMParser

    let el = (new DOMParser())
         .parseFromString('<div class="foo"></div>', 'text/html')
         .body.childNodes[0];
    

以上所有这些都正确创建元素,节点被插入到DOM中,但编辑器库不会启动。

使用jQuery,插入了元素,编辑库开始:

    let el = $('<div class="foo"></div>')

要总结一下,我不是在寻找有关实现Trix库的建议

基本上,jQuery使用Regexp和其他技巧来解析字符串的相关部分。对于您提供的示例,它将获得具有class属性的类型div元素,该属性的值为foo

然后,它使用该数据创建元素并添加与属性相对应的属性:

var element = document.createElement("div");
element.className = "foo"; // className is the DOM property equivalent to the class attribute

就是这样的示例,因为该元素没有HTML字符串指示的任何子元素

最新更新