jQuery事件处理程序不起作用

jQuery event handlers does not work?

本文关键字:不起作用 程序 事件处理 jQuery      更新时间:2023-09-26
var imgadd = $("<img/>",{
        src:"../img/Koala.jpg",
        alt:"Koala",
        id:"koala",
        click:function(){$(this).css("opacity","50%");},
        mouseenter:function(){$(this).css("hight","200px")}
    })
    $("body").append(imgadd);

为什么不工作?

代码在结构上是正确的,问题是你打了两个错别字。

  1. opacity的取值范围是0到1,而不是百分比。
  2. height拼写错误

下面是可以工作的代码:

var imgadd = $("<img/>",{
    src:"http://idordt.nl/wp-content/uploads/2014/06/wk-koala.jpg",
    alt:"Koala",
    id:"koala",
    click:function(){$(this).css("opacity","0.5");},
    mouseenter:function(){$(this).css("height","200px")}
})
$("body").append(imgadd);

和一个jsFiddle: http://jsfiddle.net/jaredcrowe/3fvht8s2/

将值改为1

var imgadd = $("<img/>",{
			src:"http://idordt.nl/wp-content/uploads/2014/06/wk-koala.jpg",
			alt:"Koala",
			id:"koala",
			click:function(){alert("hello");$(this).css("opacity","0.2");},
			mouseenter:function(){$(this).css("height","200px")}
		})
		$("body").append(imgadd);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>