隐藏div onclick不起作用

时间:2014-06-24 01:02:41

标签: jquery html

我无法使用<div>处理程序隐藏onclick

如果我使用此JavaScript:

$(document).click(function(){
    $("div#onlinefriends").fadeIn();
    $("div#srcfriend").hide();
});

它有效并显示onlinefriends div并且srcfriend div消失。为什么这个版本不起作用?

$("div#close").click(function(){
    $("div#onlinefriends").fadeIn();
    $("div#srcfriend").hide();
});

这是我的HTML:

<div id="close" style="text-align:center; border:0;">
  <h4>No match found</h4>
  <br/>
</div>

3 个答案:

答案 0 :(得分:1)

如果你的#close元素被AJAX动态地拉入你的DOM ......

$(document).on("click", "#close", function() {
    $("#onlinefriends").fadeIn();
    $("#srcfriend").hide();
});

在此处阅读更多内容:http://api.jquery.com/on/#direct-and-delegated-events

答案 1 :(得分:0)

试试这个兄弟:)

HTML

<div id="close" style="text-align:center; border:0;">
 <h4>No match found</h4>
</div>

JQuery的

$( "#close" ).on( "click", function() {
 $("#close").hide();
});

答案 2 :(得分:0)

尝试以下方法: HTML

<div id="close" style="text-align:center; border:0; background:red;"><h4>No match found</h4><br/></div>
<div id="onlinefriends" style="text-align:center; border:0; background:blue;"><h4>Online friends</h4></div>
<div id="srcfriend" style="text-align:center; border:0; background:orange;"><h4>Source friends</h4></div>

的JavaScript

$("#onlinefriends").hide();
$("#close").click(function(){
    $("#onlinefriends").fadeIn();
    $("#srcfriend").hide();
});

Live Example - JsFiddle


更新参考OP评论。 动态添加时

<div id="close"></div>

使用$ .on

的事件委托
$(document).on("click", "#close", function(){
    alert( "Dynamic Link Active" );
});
相关问题