我有一个具有匹配条件的循环事件。问题是匹配可能不止一次。我只想要第一个匹配的结果。这是一些脚本:
<div class='container_a'>
<div class='user user_name' id="user_shipment_name">John</div>
<div class='user user_type' id="user_shipment_type">Admin</div>
</div>
<div class='container_b'>
<div class='user user_name' id="user_payroll_name">Ray</div>
<div class='user user_type' id="user_payroll_type">Staff</div>
</div>
jQuery:
$(".user").each(function(i){
var user_match = $(this).first().prop("id").split("_");
if("user_name" == user_match[0] && "user_type" == user_match[2]){
// I'd like to return user_name John and user_type Admin here
}
});
我使用了.first()
,但仍然没有得到所需的输出。
当前使用的确切脚本:
$(".isBilling").each(function(i){
var input_type = $(this)[0].tagName;
var company_match = $(this).prop("id").split("_");
if(input_type == "SELECT"){
var val_billing_addr = $(this).find("option:selected").text();
}
else{
var val_billing_addr = $(this).val();
}
$(".billing").each(function(i){
var billing_match = $(this).first().prop("id").split("_");
var default_addr = company_match[0] + "_" + company_match[2] + "_" + company_match[3];
var billing_addr = billing_match[0] + "_" + billing_match[2] + "_" + billing_match[3];
if(default_addr == billing_addr){
$(this).val(val_billing_addr);
}
});
});
您可以使用循环来代替.each()
:
function foo() {
for (let user of $(".user")) {
var user_match = $(user).first().prop("id").split("_");
if("user_name" == user_match[0] && user_type[2] == user_match[2]){
return {
user_name: user_match[0],
user_type: user_match[2]
};
// I'd like to return user_name John and user_type Admin here
}
}
}
编辑
根据这些评论,一旦满足一个条件,我们似乎需要打破.ech((。我们可以通过返回false来实现这一点:
$(".billing").each(function(i){
var billing_match = $(this).first().prop("id").split("_");
var default_addr = company_match[0] + "_" + company_match[2] + "_" + company_match[3];
var billing_addr = billing_match[0] + "_" + billing_match[2] + "_" + billing_match[3];
if(default_addr == billing_addr){
$(this).val(val_billing_addr);
return false;
}
});