jQuery-如何在动态创建后添加事件 [英] Jquery - How to I add an event after dynamic create
问题描述
我正在动态创建div,然后将其附加到容器中
:var str = '<div class="dimsdiv" id="'+dim.src+'" cursor:pointer;"></div>';
$('#fpdiv').append(str);
现在,我需要向这些div添加一个悬停.我尝试仅引用它,但随后发现我需要考虑使用.on().我尝试过此操作(之前):
$('#'+dim.src).hover(function{},function{});
但是,正如预期的那样,这没有用.我也尝试过这个:
$('#'+dim.src).on('hover','(function{},function{})');
,但似乎无法正确获得语法.有人可以帮忙吗? 预先感谢.
您可以尝试
var str = $('<div/>', {
text:'Hello',
class:'dimsdiv',
id:'dim_src',
style:'cursor:pointer',
mouseenter:function(){ ... },
mouseleave:function(){ ... }
});
$('#fpdiv').append(str);
还从dim.src
中删除.
,而是将dim_src
用作id
,它在jQuery中用作class
选择器,不确定为什么要使用它,但$('#'+dim.src)
无效.>
演示 .
I am creating a div dynamically, then appending it to a container:
var str = '<div class="dimsdiv" id="'+dim.src+'" cursor:pointer;"></div>';
$('#fpdiv').append(str);
Now I need to add a hover even to those divs. I tried to just reference it, but then found that I needed to consider .on() instead. I tried this (before on):
$('#'+dim.src).hover(function{},function{});
But as expected, that didn't work. I also tried this:
$('#'+dim.src).on('hover','(function{},function{})');
but can't seem to get the syntax just right. Can someone help here? Thanks in advance.
You may try this
var str = $('<div/>', {
text:'Hello',
class:'dimsdiv',
id:'dim_src',
style:'cursor:pointer',
mouseenter:function(){ ... },
mouseleave:function(){ ... }
});
$('#fpdiv').append(str);
Also remove the .
from dim.src
, instead use dim_src
as id
, it's used as class
selector in jQuery, not sure why you used it tho but $('#'+dim.src)
is invalid.
DEMO.
这篇关于jQuery-如何在动态创建后添加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!