我有这段代码,可以通过ajax从数据库检索数据,并且可以添加无限的文本字段:
<div class="input" id="itemRows">
<div class="clone">
<style>
.txtHint {
width:95%;
padding:10px 6px;
border-bottom:solid 3px #06C;
background-color:#f1f1f1;
margin-right:5px;
}
</style>
<input onchange="showUser(this.value)" type="text" class="clientphone" placeholder="رقم العميل" name="clientmergedid[]" />
<input type="text" class="clientdes" placeholder="صفة العميل" name="clientmergeddes[]" />
<div class="clearfloat"></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "searchuser/getuser.php?clientmergedid=" + str, true);
xmlhttp.send();
}
</script>
<div id="txtHint" class="txtHint">بيانات العميل</div>
<div class="clearfloat"></div>
</div> <a href="#" class="add" rel=".clone">إضافة المزيد</a>
<script type="text/javascript">
$(function() {
var removeLink = ' <a class="remove" href="#" onclick="$(this).parent().slideUp(function(){ $(this).remove() }); return false">إزالة</a>';
$('a.add').relCopy({
append: removeLink
});
});
</script>
<div class="clearfloat"></div>
<input onClick="addRow(this.form);" class="clientadd" type="button" value="جديد" />
<div class="clearfloat"></div>
</div>
问题是它只能检索第一个 txtHint
div 的数据。它如何对其他输入进行同样的操作?
最佳答案
对于您最初的问题,为每个输入提供一个类,然后将 change
处理程序绑定(bind)到该类的元素。这样你就可以让任意数量的输入具有这种行为:
<input class="my_class" type="text">
<input class="my_class" type="text">
jQuery(function () {
jQuery('.my_class').on('change', function () {
var the_input = jQuery(this);
console.log("My new value is " + the_input.val());
/// your ajax code goes here, and has access to the_input
});
});
示例如下:http://jsfiddle.net/3k3TL/
此外,由于您似乎已经在使用 jQuery,我建议使用它的 .get()您的 ajax 调用的方法而不是现有代码。
关于javascript - 如何重复通过ajax检索数据的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22377850/