Error in console while hiding the link on click through Polymer/Dom

主宰稳场 提交于 2020-01-25 01:22:10

问题


Hi Stack Overflowians,

I want to hide the Click foo link when I click the same Click foo link.

I have the following code:

<dom-module>
    <div id="foo">
        <a href="#" onclick="toggle_visibility('foo');">Click foo</a>
    </div>

<script>
    Polymer({
        is: 'test-file',

        toggle_visibility: function(id) {
            var e = document.getElementById(id);

            if (e.style.display === "none") {
                e.style.display = "block";
            } else {
                e.style.display = "none";
            }
        });
</script>
</dom-module>

I get the error in Console tab when I click on Click foo link:

Uncaught ReferenceError: toggle_visibility is not defined at HTMLAnchorElement.onclick

I want the link to hide when clicked on Click foo link

Can anyone please help ?

Thanks in advance


回答1:


In Polymer you declaratively add event handlers by using on- + the event name. So in your case that would be on-click, not onclick.

Also, you will need to provide the name for a method, not to call it. So your a tag would become something like:

<a href="#" on-click="toggle_visibility">Click foo</a>

Since that doesn't pass a paramter you can find another way, like using a data- attribute, or maybe if the relationship to the anchor is the same every time just rely on the fact that the div is the parent node:

toggle_visibility: function(event) {
    var e = event.currentTarget.parentNode;

    if (e.style.display === "none") {
        e.style.display = "block";
    } else {
        e.style.display = "none";
    }
}

UPDATE: also note that, if you go by using a method that would query for the element to toggle the display for, you will most likely have to query the shadowDom, not the document level. So

var e = document.getElementById(id);

would become:

var e = this.shadowRoot.getElementById(id);


来源:https://stackoverflow.com/questions/58480094/error-in-console-while-hiding-the-link-on-click-through-polymer-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!