[英]Why the click function doesn't work in jQuery?
I am trying to do something when I click on the div or class "c" but it seems that it does not work. 当我单击div或类“ c”时,我正在尝试执行某些操作,但似乎不起作用。 any suggestion how I can fix it? 有什么建议我可以解决吗?
<html>
<head>
<title>My seconf jQuery practice</title>
<style>
.c {
width: 100px;
height:100px;
border-radius: 50px;
background-color: red;
}
</style>
</head>
<body>
<div class="c"></div>
<p>My text
<script "type=text/javascript" src="jquery-min.js">
$(".c").click(function() {
//$("p").html("my text has changed");
alert('hi');
});
</script>
</body>
</html>
Your script tags are wrong, should be as follows: 您的脚本标签有误,应如下所示:
<script type="text/javascript" src="jquery-min.js"></script>
<script type="text/javascript">
$(".c").click(function() {
//$("p").html("my text has changed");
alert('hi');
});
</script>
And you probably will have to add a slash to the src if you get a 404: 如果您收到404,则可能必须在src中添加一个斜杠:
<script type="text/javascript" src="/jquery-min.js"></script>
Note that you've written "type=text/javascript"
and it should be type="text/javascript"
请注意,您已编写"type=text/javascript"
,并且应为type="text/javascript"
It's likely that the content in your script tag is being ignored . 您的script标记中的内容可能会被忽略 。 Include JQuery and your content script separately. 分别包含JQuery和内容脚本。
<script type="text/javascript" src="/jquery-min.js"></script>
<script type="text/javascript">
$(function() {
$(".c").click(function()
{
//$("p").html("my text has changed");
alert('hi');
});
});
</script>
Also as mentioned below, you want to wait until the document ready event to try do anything against the dom. 同样如下所述,您想等到文档准备事件尝试对dom执行任何操作。
I fixed your code as below. 我将您的代码固定如下。
<html> <head> <title>My second jQuery practice</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <style> .c{ width: 100px; height:100px; border-radius: 50px; background-color: red; } </style> <script> $(document).ready(function() { $(".c").click(function() { alert("You clicked on a div."); }); }); </script> </head> <body> <div class="c"></div> <p> My text </p> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.