无法在javascript

问题描述

我正在使用LWC框架来开发组件。它基于ES6 Standard。我正在尝试使用XSLTProcessor来满足我的要求之一,但这给我一个错误

无法构建“ XSLTProcessor”:请使用“ new”运算符, 此DOM对象构造函数不能作为函数调用

代码

import { LightningElement } from 'lwc';

export default class displayReport extends LightningElement {
    handleOnClick(){        
        if(window.XSLTProcessor){
            console.log('XSLTProcessor TRUE')// Working
            try
            {
            var xsltProcessor = new window.XSLTProcessor();
            console.log('XSLTProcessor WORKING') // Not coming here
            }
            catch(e){
                console.log(e.message); //Error displayed
            }
        }
        if(window.DOMParser){
            console.log('DOMParser TRUE')
            try
            {
            var parser = new window.DOMParser();
            console.log('DOMParser WORKING') //This is working
            }
            catch(e){
                console.log(e.message); //No Errors
            }
        }
    }
}

我不确定为什么XSLTProcessor不起作用,但是DOMParser起作用。

解决方法

https://developer.salesforce.com/docs/component-library/tools/playground,对我来说,例如my-button.html

<template>
    <div>
        <input type="button" value="test" onclick={handleClick}>
        <div class="xslt-output" lwc:dom="manual"></div>
    </div>
</template>

my-button.js

import { LightningElement } from 'lwc';

export default class MyButton extends LightningElement {

  handleClick() {
      const xsltProc = new XSLTProcessor();
      const xsltCode = `<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="html" indent="yes"/>
  <xsl:template match="list">
    <section>
      <h2>XSLTProcessor test</h2>
      <ul style="list-style-type: disc;">
        <xsl:apply-templates/>
      </ul>
    </section>
  </xsl:template>
  <xsl:template match="item">
    <li>
      <xsl:apply-templates/>
    </li>
  </xsl:template>
</xsl:stylesheet>`;
      const xmlCode = `<list>
    <item>foo</item>
    <item>bar</item>
  </list>`;
      const domParser = new DOMParser();
      const xsltDoc = domParser.parseFromString(xsltCode,'application/xml');
      const xmlDoc = domParser.parseFromString(xmlCode,'application/xml');
      xsltProc.importStylesheet(xsltDoc);

      const container = this.template.querySelector('div.xslt-output');

      container.appendChild(xsltProc.transformToFragment(xmlDoc,container.ownerDocument));
  }
}

然后在app.html内部,我可以使用<c-my-button></c-my-button>,然后单击按钮,将执行XSLT并插入其结果。