2012-02-03 41 views
0

有没有人有任何想法我可以做错什么?为什么这个基本的点击功能没有被执行到发送警报的地步。我有jQuery-1.7.1.js链接到我的页面。基本.click功能我无法工作jQuery

jQuery的

<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 


<script type="text/javascript" src="../fruith/jquery-1.7.1.js"></script> 

<script type="text/javascript"> 
function checkedDark() { 

$('#activate_post_checkbox').click(function(){ 
    alert('duh') 

    $('#work').css('color', this.checked ? '#000' : '#666'); 

}); 


} 
</script> 

</head> 

HTML

<body> 
<div id="work">blah blah blah</div> 


<input type="checkbox" id="activate_post_checkbox" value="active" /><span id="activate_post_checkbox_text">Make my posting active immediately.</span> 
</body> 
</html> 

回答

6

您需要在document.ready功能分配click事件,还是先打电话给你checkedDark()功能。

例如:

<script type="text/javascript"> 
$(function() { 

    $('#activate_post_checkbox').click(function(){ 
     alert('duh'); 
     $('#work').css('color', this.checked ? '#000' : '#666'); 
    }); 
}); 
</script> 
+0

ya def需要document.ready谢谢大家 – noWayhome 2012-02-03 22:16:48

0
function checkedDark() { 

$('#activate_post_checkbox').click(function(){ 
    alert('duh') 

    $('#work').css('color', this.checked ? '#000' : '#666'); 

}); 


} 
checkedDark(); 
1

对于一个你定义一个函数听众。也许这应该是文件准备好。

$(document).ready(function() { 

$('#activate_post_checkbox').click(function(){ 
    alert('duh') 

    $('#work').css('color', this.checked ? '#000' : '#666'); 

}); 


}); 

也,你可能要考虑使用。点击的。对,而不是因为这是更晚的jQuery版本标准的...

$('#activate_post_checkbox').on('click', function(){ 
    alert('duh') 

    $('#work').css('color', this.checked ? '#000' : '#666'); 

}); 
0
<script type="text/javascript"> 
$(function(){ 

    $('#activate_post_checkbox').click(function(){ 
     alert('duh') 

     $('#work').css('color', this.checked ? '#000' : '#666'); 

    }); 

}); 
</script> 
0

因为在绑定到click事件时,DOM尚未准备好。 移动脚本文件结束或由$(document).ready(function() { ... });把它包:当执行checkedDark方法

$(document).ready(function() { 
    // your code here 
}); 
0

click事件处理程序将只被附接。我没有看到这个方法在你的页面中被调用。

在页面加载时执行它将附加处理程序。尝试这个。

$(function(){ 

    $('#activate_post_checkbox').click(function(){ 
     alert('duh');//Though its not the issue but add the semicolon 
     $('#work').css('color', this.checked ? '#000' : '#666'); 
    }); 

}); 

或者这样做。

$(checkedDark); 

或者在关闭body标签前调用页面末尾的函数,以便元素可用于jQuery。

checkedDark(); 
0

你可以叫checkedDark(),把click事件里面或使外单击checkedDark功能

function checkedDark() { 

} 

$('#activate_post_checkbox').click(function(){ 
    alert('duh') 

    $('#work').css('color', this.checked ? '#000' : '#666'); 

}); 
0

你是不是调用checkedDark功能,并没有处理程序被连接到对应的复选框事件。另外,您还需要确保页面上的元素已准备就绪。使用.on()方法而不是click()。

(function checkedDark() { 

$('#activate_post_checkbox').on('click', function(){ 
    alert('duh'); 

    $('#work').css('color', this.checked ? '#000' : '#666'); 

}); 

}());