Inf*_*i7y 0 javascript ajax jquery onclick
我正在尝试使用以前存储的值将变量传递给 onClick 函数。我有一个数据库设置,可以在提供邮政编码时搜索商店位置。例如,在用户搜索邮政编码后,使用 ajax 调用生成以下链接。返回值“WAFHOH3”是与该特定商店关联的 ID:
生成的链接:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Run Code Online (Sandbox Code Playgroud)
基于此代码:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果返回数字以外的任何内容,我会收到“未捕获的引用错误:WAFHOH3 未定义”控制台错误。当像下面的示例一样传递一个数字时,一切正常,我没有收到任何错误,并且应用程序继续按预期工作。
例如(这有效):
我尝试手动将字符串更改为数字,只是为了隔离任何与数据库相关的问题。我唯一的猜测是我的代码中有些东西可能试图将输入验证为数字。
ajax 调用的完整代码如下。
完整代码:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at <a href="mailto:admin@admin.com">admin@admin.com</a> for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at <a href="mailto:sadmin@admin.com">admin@admin.com</a> for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
Run Code Online (Sandbox Code Playgroud)
您需要将输入item.store_code用引号引起来;否则,它会尝试将其视为变量,而不是字符串:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Run Code Online (Sandbox Code Playgroud)
click理想情况下,您可以在为按钮指定一个类(例如 )后附加一个处理程序register:
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
Run Code Online (Sandbox Code Playgroud)