Вопрос

I'm trying to implement the features from this site. But my code isn't alerting anything when I click on the x-foo element. Here is my code:

<!DOCTYPE html>
<html>
<head>
<title>
    Test
</title>
</head>
<body>
<script type="text/javascript">
    var xFoo = document.createElement('x-foo');
    var xFoo = new XFoo();
    document.body.appendChild(xFoo);
    xFoo.onclick=function(){alert("It works!")};
</script>
<x-foo>
    Test
</x-foo>
</body>
</html>

Any suggestions? (I'm on Chrome)

Это было полезно?

Решение

It looks like you're trying to create a Custom Element but you haven't registered it yet. To create your own XFoo element would look something like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>My Custom Element</title>
  </head>
  <body>
    <!-- Create a template for the content inside your element -->
    <template>
      <h1>Hello from XFoo</h1>
    </template>

    <!-- Register your new element -->
    <script>
    var tmpl = document.querySelector('template');

    var XFooProto = Object.create(HTMLElement.prototype);

    XFooProto.createdCallback = function() {
      var root = this.createShadowRoot();
      root.appendChild(document.importNode(tmpl.content, true));
    };

    var XFoo = document.registerElement('x-foo', {
      prototype: XFooProto
    });
    </script>

    <!-- Use the element you've just registered as a tag -->
    <x-foo></x-foo>

    <!-- OR, create an instance using JavaScript -->
    <script>
    var el = document.createElement('x-foo');
    document.body.appendChild(el);
    </script>
  </body>
</html>

Unfortunately this approach depends on native APIs which currently only ship in Chrome 34. As someone else mentioned, a much easier approach to creating your own custom element would be to use Polymer. Polymer is a library that adds support for Web Components (essentially what you're trying to build) to all modern browsers. That includes IE 10+, Safari 6+, Mobile Safari, current Chrome and current Firefox.

I've put together a jsbin which shows how to create your own x-foo element using Polymer.

Другие советы

You should try viewing the following article:

http://www.polymer-project.org/

It's an open source Github project. I actually tried that article, but don't recommend it. Instead, use the link given above. It uses Ajax and JSON.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top