【问题标题】:How to set inner text of tag in web component如何在 Web 组件中设置标签的内部文本
【发布时间】:2014-11-25 13:50:33
【问题描述】:

我正在使用 x-tags。这是我正在处理的代码。我需要使用自定义元素属性值的值设置这些 div 框的内容。是否有可能做到这一点?我尝试设置它,但出现错误“未定义不是函数”。

var template = xtag.createFragment(function(){/*
  <div>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
  </div>
*/});

xtag.register('x-navbar', {
  lifecycle: {
    created: function() {
      this.appendChild(template.cloneNode(true));
      this.getElementById("#box1").innerHTML = this.productName;
    },
  accessors: {
    productName: {
      attribute: {},
      get: function(){
        return this.getAttribute('productName') || "";
      },
      set: function(value){
        this.xtag.data.header.setAttribute('productName',value);
      }
    }
  }
});

<x-navbar productName="Box 1">hii</x-navbar>

【问题讨论】:

  • 检查你的括号。您有未分配的变量。不需要 created 的第 2 行。您需要在 productName 设置器中设置该元素。

标签: javascript html web-component custom-element x-tag


【解决方案1】:

您可以进一步简化此操作,因为您没有更改 setter 中的 productName:

xtag.register('x-navbar', {
  content: function() {/*
  <div>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
  </div>
*/},
  accessors: {
    productName: {
      attribute: {},
      set: function (name) {
        this.querySelector('#box1').textContent = name;
      }
    }
  }
});

你会这样使用:

<x-navbar product-name="Testing 123">hii</x-navbar>

请注意,属性名称必须是 productNameproduct-name 的破折号版本。这将呈现为:

hii
Testing 123

模板&lt;div&gt;结构添加在元素内容hii之后。

【讨论】:

    【解决方案2】:

    您可以像这样编写属性支持访问器。您不需要手动尝试设置属性。因为它会更新自己,从 get 函数返回值。

    accessors: {
                productName: {
                    attribute: {},
                    get: function () { return this._productName; },
                    set: function (value) { 
                         this._productName = value;
                         // MANUPLATE YOUR HTML IN HERE
                         this.getElementById("#box1").innerHTML = this.productName;
                    }
                },
    }
    

    【讨论】:

    • 这似乎很容易出现 XSS - 想象一下产品名称 &lt;script&gt;alert("evil")&lt;script&gt;...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 2014-02-10
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多