【问题标题】:DOM element exists, jQuery can't manipulate itDOM 元素存在,jQuery 无法对其进行操作
【发布时间】:2015-08-03 18:14:44
【问题描述】:

我有这个事件处理程序,我可以记录 DOM 元素,但我不能用它做任何事情。设置显示或任何东西都没有任何效果。

 Template.layoutTemplate.events({
   'mouseover .top_nav_button': function(ev){
    ev.preventDefault();


    console.log($(this).css('padding'));

    $(this).css('display', 'none');

}

});

这是模板代码:

<template name = 'layoutTemplate'>
    <div id = 'top_nav'>
        {{> loginButtons}}
        <a class='top_nav_button' id = 'about_snipex_button' href="{{pathFor 'about'}}">About Snipex</a>
        <a class='top_nav_button' id = 'become_verified_button' href="{{pathFor 'verified'}}">Become Verified!</a>
        <a class='top_nav_button' id = 'terms_button' href="{{pathFor 'terms'}}">Terms&Conditions</a>
    </div>
    <h1 id='layout_header'><a id = 'home_button' href="{{pathFor 'home'}}">snippetExchange</a></h1>
    <div id='layout_header_row_2'>
        <h2 id='layout_by_line'><a id = 'home_button' href="{{pathFor 'home'}}">valuable answers</a></h2>
    </div>
    <div id='sub_nav'>
        <a class='sub_nav_button' id = 'notifications_button' href="{{pathFor 'notifications'}}">notifications</a>
        <a class='sub_nav_button' id = 'my_history_button' href="{{pathFor 'user_profile' _id=currentUser}}">my history</a>
        <a class='sub_nav_button' id = 'new_post_button' href="{{pathFor 'new_post'}}">new post</a>
    </div>
    {{> yield}}
</template>

【问题讨论】:

    标签: javascript jquery css meteor


    【解决方案1】:

    display 规则没有 hidden 的值。

    改成$('#top_nav').css('display', 'none');

    Hidden 是 css 中 visibility 规则的属性。

    【讨论】:

    • 那是我乱搞...现在检查那里的代码示例
    • 我得到Uncaught TypeError: Cannot use 'in' operator to search for 'padding' in undefined ...该元素在我的样式表中有属性填充
    • 您可能会收到该错误,因为 $this 元素不是您所期望的。尝试做一个 console.log($this) 来确保你有什么。
    【解决方案2】:

    使用hide():

    $('#top_nav').hide();
    

    【讨论】:

      【解决方案3】:

      事件监听器有两个参数:eventtemplate

      您可以通过以下方式找到您要查找的元素:

      'mouseover .top_nav_button': function(event, template){
        event.preventDefault(); // likely not needed
        template.$('#top_nav').hide();
        // OR
        template.$('#top_nav').css('display', 'none');
      }
      

      如果您需要定位触发事件的元素,请使用:

      'mouseover .top_nav_button': function(event, template){
        event.preventDefault(); // likely not needed
        var elem = event.target;
        template.$(elem).hide();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-27
        • 2016-08-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多