通过 jQuery 动态添加 HTML 元素后的额外点击
Extra click after dynamically added HTML elements via jQuery
我在data.html
中动态添加了一些html
<div class="d-flex " id="deviceSeearchRecords">
<div class="p-2 flex-grow-1 ">
<button type="button" class="btn deviceName " data-href="@Url.Content(string.Format(" ~/Devices/Details/{0} ", @item.ID))">
@item.FullName
</button>
</div>
</div>
在此之后我假设使用这样的点击事件。
$('#searchResultContainer').html('');
$.getJSON('@Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
$('#searchResultContainer').append(data.html);
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
}
});
但是当我第一次点击时没有任何反应。第二次单击时,它可以正常工作。
我曾尝试在 div
上使用 focus()
,但如果没有帮助。
这种方法也没有帮助
我在这里遗漏了什么?
将您的代码移至外部
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
感谢大家!
我在这里找到了我的解决方案
Is it possible to focus on a <div> using JavaScript focus() function?
所以我只是在 data.html
中使用常规 <a>
,然后在 div
上使用动态添加的数据 focus
。一键生效!
$('#searchResultContainer').html('');
$.getJSON('@Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
if (data.success === true) {
$('#searchResultContainer').html(data.html);
window.location.hash = '#searchResultContainer';
}
}
});
我在data.html
<div class="d-flex " id="deviceSeearchRecords">
<div class="p-2 flex-grow-1 ">
<button type="button" class="btn deviceName " data-href="@Url.Content(string.Format(" ~/Devices/Details/{0} ", @item.ID))">
@item.FullName
</button>
</div>
</div>
在此之后我假设使用这样的点击事件。
$('#searchResultContainer').html('');
$.getJSON('@Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
$('#searchResultContainer').append(data.html);
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
}
});
但是当我第一次点击时没有任何反应。第二次单击时,它可以正常工作。
我曾尝试在 div
上使用 focus()
,但如果没有帮助。
这种方法也没有帮助
我在这里遗漏了什么?
将您的代码移至外部
$(document).on('click', '.deviceName', function(e) {
e.preventDefault();
e.stopPropagation();
// console.log('deviceName ' + $(this).data('href'));
window.location.href = $(this).data('href');
});
感谢大家!
我在这里找到了我的解决方案 Is it possible to focus on a <div> using JavaScript focus() function?
所以我只是在 data.html
中使用常规 <a>
,然后在 div
上使用动态添加的数据 focus
。一键生效!
$('#searchResultContainer').html('');
$.getJSON('@Url.Action("Search", "Devices")', {
s: $('#searchStr').val()
},
function(data) {
if (data.success === true) {
if (data.success === true) {
$('#searchResultContainer').html(data.html);
window.location.hash = '#searchResultContainer';
}
}
});