控制台中的错误,同时隐藏了通过Polymer/Dom的点击链接 [英] Error in console while hiding the link on click through Polymer/Dom

查看:68
本文介绍了控制台中的错误,同时隐藏了通过Polymer/Dom的点击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stack Overflowians,

Hi Stack Overflowians,

当我单击同一Click foo链接时,我想隐藏Click foo链接.

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

我有以下代码:

<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>

单击Click foo链接时,在控制台"选项卡中出现错误:

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

Uncaught ReferenceError: toggle_visibility is not defined at HTMLAnchorElement.onclick

我希望在单击Click foo链接时隐藏该链接

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

任何人都可以帮忙吗?

预先感谢

推荐答案

在Polymer中,您可以使用on- +事件名称声明性地添加事件处理程序.因此,在您的情况下为on-click,而不是onclick.

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>

由于没有传递参数,您可以找到另一种方式,例如使用data-属性,或者如果每次与锚点的关系相同,则仅依赖于div是父节点这一事实:

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";
    }
}

更新:还请注意,如果使用一种查询元素来切换显示的方法,则很有可能必须查询shadowDom,而不是文档级别.所以

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);

将成为:

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

这篇关于控制台中的错误,同时隐藏了通过Polymer/Dom的点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆