jquery 在 IE11 中点击无法处理动态添加的 href
jquery click not working on dynamically added hrefs in IE11
您好,我的 HTML 代码中有一些 link。我想在悬停时更改每个 link 的 href 属性,然后单击此 link 我想在新选项卡中打开它。代码如下:
$('.identifierClass').hover(function(e) {
if(condition) // is true
{
$(element).attr("href", "url/goes/here").off().click(function(e) {
$(element).attr("target", "_blank");
});
}
});
在 Chrome/Firefox 中一切正常,但是,在 IE 11 中单击 link 时它只是挂起并且单击不起作用。
感谢任何帮助。
您需要绑定到将在其中创建动态元素的静态或预先存在的元素:
$(document).on('mouseenter','.identifierClass',function(e) {
if(condition) // is true
{
$(element).attr("href", "url/goes/here").attr("target", "_blank");
}
});
编辑:这里是 fiddle of it and I also had to use 'mouseenter' instead of 'hover' when using the string name for the event. jquery .hover() documentation
在 fiddle 中,我向您展示了两个正在动态添加的 div:
$('#place').html('<div class="identifierClass">hover1</div><div class="identifierClass2">hover2</div>');
在此之上,我为 hover1 div 设置了我的事件处理程序,我使用指定的选择器在文档上设置了事件:
$(document).on('mouseenter','.identifierClass',function(e) {
alert('hi');
});
当您将鼠标悬停在右侧的 'hover1' 文本上时,您可以看到它有效,相反,您可以看到 hover2 使用此绑定不起作用:
$('.identifierClass2').hover(function(e) {
alert('hi2');
});
here 是 jquery 事件委托文档的 link。
Edit2:我更新了 fiddle 以解决 'href' 操作。您似乎只想更改悬停部分的一些属性:
我将 'mouseenter' 绑定修改为如下所示:
$(document).on('mouseenter','.identifierClass',function(e) {
alert('hi'); $('#someLink').attr('href','http://www.bing.com').attr('target','_blank');
});
我认为您不需要 'off' 或 'click',但这是基于一些假设,所以请随时发表评论,我会相应地进行更新。但是,这会在鼠标进入动态元素时更改 href 并同时更改目标属性。
您好,我的 HTML 代码中有一些 link。我想在悬停时更改每个 link 的 href 属性,然后单击此 link 我想在新选项卡中打开它。代码如下:
$('.identifierClass').hover(function(e) {
if(condition) // is true
{
$(element).attr("href", "url/goes/here").off().click(function(e) {
$(element).attr("target", "_blank");
});
}
});
在 Chrome/Firefox 中一切正常,但是,在 IE 11 中单击 link 时它只是挂起并且单击不起作用。
感谢任何帮助。
您需要绑定到将在其中创建动态元素的静态或预先存在的元素:
$(document).on('mouseenter','.identifierClass',function(e) {
if(condition) // is true
{
$(element).attr("href", "url/goes/here").attr("target", "_blank");
}
});
编辑:这里是 fiddle of it and I also had to use 'mouseenter' instead of 'hover' when using the string name for the event. jquery .hover() documentation
在 fiddle 中,我向您展示了两个正在动态添加的 div:
$('#place').html('<div class="identifierClass">hover1</div><div class="identifierClass2">hover2</div>');
在此之上,我为 hover1 div 设置了我的事件处理程序,我使用指定的选择器在文档上设置了事件:
$(document).on('mouseenter','.identifierClass',function(e) {
alert('hi');
});
当您将鼠标悬停在右侧的 'hover1' 文本上时,您可以看到它有效,相反,您可以看到 hover2 使用此绑定不起作用:
$('.identifierClass2').hover(function(e) {
alert('hi2');
});
here 是 jquery 事件委托文档的 link。
Edit2:我更新了 fiddle 以解决 'href' 操作。您似乎只想更改悬停部分的一些属性:
我将 'mouseenter' 绑定修改为如下所示:
$(document).on('mouseenter','.identifierClass',function(e) {
alert('hi'); $('#someLink').attr('href','http://www.bing.com').attr('target','_blank');
});
我认为您不需要 'off' 或 'click',但这是基于一些假设,所以请随时发表评论,我会相应地进行更新。但是,这会在鼠标进入动态元素时更改 href 并同时更改目标属性。