gpt4 book ai didi

java - Jquery在循环中设置索引位置html标签的值

转载 作者:行者123 更新时间:2023-12-01 14:46:35 24 4
gpt4 key购买 nike

我有一个ajax调用,我想在成功函数中循环遍历类中的每个标签并将它们的值设置为从服务器响应返回的值。下面是代码,但是这将所有标签设置为相同的值,这不是我想要的,我想访问该项目的索引并仅将该索引设置为响应值。我哪里出错了?:

JQuery:

 function GetCitizenTypeDescription(citizenTypeId){                 
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeDesc').each(function(i){
alert(data);
$('.citizenTypeDesc').text(data);
});
}


});

}


$(document).ready(function() {


$(".photos").each(function(i){

if ($(this).val() != '') {
var image = new Image();
image.src = $(this).val();

image.onload = function(){

var ctx = document.getElementsByClassName("canvas")[i].getContext('2d');
ctx.drawImage(image,0,0, 320, 240);
}
}



});

$('.citizenTypeDesc').each(function(i){

var citizenTypeId = document.getElementsByClassName("citizenTypeId")[i].value;
GetCitizenTypeDescription(citizenTypeId);

});


});

控制台返回正确的数据,我只需要将其写入标签

控制台:

GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=2 200 OK 174ms
Response
CRIMINAL

GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=3 200 OK 174ms
Response
VICTIM

GET http://localhost:8084/crimeTrack/getCitizenTypeDescription.htm?citizenTypeId=4 200 OK 174ms
Response
....

html

</head>
<body>
<div id ="content">
<c:forEach items="${citizens}" var="citizen">
<div id="table">
<div>
<p><canvas class="canvas" height="240" width="320"></canvas>
</div>
<a href="citizen_registration.htm">Name:- ${citizen.fName} ${citizen.lName}</a>
<input type="hidden" id="photo" value="${citizen.photo}" class="photos"/>
<input type="hidden" id="socialSecurityNumber" value="${citizen.socialSecurityNumber}" />
<input type="text" class="citizenTypeId" value="${citizen.citizenTypeId}"/>
<label class="citizenTypeDesc"></label>
</div>
</c:forEach>
</div>
</body>
</html>

最佳答案

您可以循环遍历所有.citizenTypeId,而不是循环遍历所有.citizenTypeDesc标签。测试每个值是否与参数匹配,然后设置同一父元素内的标签。

function GetCitizenTypeDescription(citizenTypeId){                 
$.ajax({
type:'GET',
url:'getCitizenTypeDescription.htm',
data:{citizenTypeId:citizenTypeId},
dataType: 'text',
success: function (data) {
$('.citizenTypeId').each(function(i){
//does this value match the parameter
if($(this).val() === citizenTypeId){
//find the parent div, in this case .table
var parent = $(this).parent();
//search for a child with class .citizenTypeDesc
var thisCitizenTypeDesc = parent.children('.citizenTypeDesc');

thisCitizenTypeDesc.text(data);
}
});
}
});
}

关于java - Jquery在循环中设置索引位置html标签的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390589/

24 4 0