gpt4 book ai didi

javascript - JQuery 动态按钮

转载 作者:行者123 更新时间:2023-11-29 16:06:13 25 4
gpt4 key购买 nike

我有一个输入框。我输入搜索词并返回值。我想要做的是单击带有附加值的动态按钮。但是,当我单击按钮时,它会重新加载页面而不是显示警告框。这只发生在动态按钮上,而不是搜索按钮

$(document).ready(function () {
$('.cta-button').click(function () {
event.preventDefault();
alert("You clicked the button");
});

$('#searchButton').click(function () {
event.preventDefault();
var varSearch = $('#searchDB').val();
if (!varSearch) {
$('#result').html("Please enter a search term");
return;
}
$.ajax({
contentType: "application/json; charset=utf-8",
data: 'ID=' + varSearch,
url: "getTest.ashx",
dataType: "json",
success: function (data) {
var result = '';
$.each(data, function (index, value) {
result += '' +
'<div class="main-area bg-white">' +
'<div class="row">' +
'<div class="medium-6 columns">' +
'<button type="submit" id="OfferID_' + index + '" class="cta-button cta-button-icon">Add to Cart</button>' +
'<br />' +
'</div>' +
'</div>' +
'</div>'
});
if (!result) {
result = 'No data were found for ' + varSearch;
};

$('#result').html(result);
}
});
});
});


<section>
<div class="row">
<div class="medium-4 columns medium-centered">
<div class="search-rewards">
<input type="search" id="searchDB" />
<button type="submit" id="button" class="button"></button>
</div>
</div>
</div>
<div class="row">
<div class="medium-6 columns medium-centered">
<div id="result">

</div>
</div>
</div>
</section>

最佳答案

您缺少 click 函数的 event 参数。没有它,event.preventDefault() 什么都不做。

$('.cta-button').click(function(event) {
event.preventDefault();
alert("You clicked the button");
});

更新

要绑定(bind)到动态按钮,您需要按照@MACMAN 的建议使用委托(delegate):

$(document).on('click', '.cta-button', null, function(event){
event.preventDefault();
alert("You clicked the button");
});

关于javascript - JQuery 动态按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41436258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com