简体   繁体   中英

jQuery .live function not working

Can somebody please tell me why this script is not working? It is supposed to work, but it doesn't, I am getting the id correctly, but Divs are not displaying properly. My idea is to display one div based on the click, and hide the other Divs.

Script

$(document).ready(function() {
    $("a").live("click", function(){
    var idV = $(this).attr("id"); 
    alert(idV);
    $("#"+idV+"div").css("display","block");
    return false;
    });
});

HTML

<a href="#" id="solution1">Solution 1</a>
<a href="#" id="solution2">Solution 2</a>
<a href="#" id="solution3">Solution 3</a>
<a href="#" id="solution4">Solution 4</a>
<br />

<div id="solution1" style="display:none;">Solution 1</div>
<div id="solution2" style="display:none;">Solution 2</div>
<div id="solution3" style="display:none;">Solution 3</div>
<div id="solution4" style="display:none;">Solution 4</div>

Your div ids are wrong. Try:

<div id="solution1div" style="display:none;">Solution 1</div>

instead of

<div id="solution1" style="display:none;">Solution 1</div>

Edit:

JSBIN: Preview

JSBIN: Source Code

<a href="javascript:;" id="solution1">Solution 1</a> 
<a href="javascript:;" id="solution2">Solution 2</a> 
<a href="javascript:;" id="solution3">Solution 3</a> 
<a href="javascript:;" id="solution4">Solution 4</a> 
<br /> 

<div> 
<div id="solution1div" style="display:none;">Solution 1</div> 
<div id="solution2div" style="display:none;">Solution 2</div> 
<div id="solution3div" style="display:none;">Solution 3</div> 
<div id="solution4div" style="display:none;">Solution 4</div> 
</div> 

jquery:

$("a").live("click", function(){ 
var idV = $(this).attr("id");  

$("#"+idV+"div").siblings().hide(); 
$("#"+idV+"div").show(); 

return false; 
}); 

mmmm the error is actually there man..

see:

$("#"+idV+".div").css("display","block");

change it to:

$("div#"+idV).css("display","block");

You're reusing ID attributes. IDs need to be unique to a document.

You can't have anchors and divs with the same ID.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM