我正在为如何正确应用.closest而苦苦挣扎
一系列的输入被用来记录一组网球的得分。如果用户输入7-6或6-7组合,则会出现隐藏的div,以便他们可以记录抢七。
我只想让最接近当前输入的隐藏tiebreak div出现。
这是我到目前为止所知道的:
$(document).ready(function() {
var div = $('.tiebreakfield');
$('.score1, .score2').keyup(function() {
var value1 = parseInt($(".score1").val());
var value2 = parseInt($(".score2").val());
if ((value1 == 6 || value1 == 7) && (value2 == 6 || value2 == 7) && (value1 !== value2)) {
div.fadeIn();
} else {
div.fadeOut();
}
});
});
$(document).ready(function() {
var div = $('.tiebreakfield');
$('.score3, .score4').keyup(function() {
var value1 = parseInt($(".score3").val());
var value2 = parseInt($(".score4").val());
if ((value1 == 6 || value1 == 7) && (value2 == 6 || value2 == 7) && (value1 !== value2)) {
div.fadeIn();
} else {
div.fadeOut();
}
});
});
如果输入7-6组合,上面的代码显示了所有隐藏的div。
这里有一个例子...http://jsfiddle.net/jQHDR/
发布于 2013-07-26 02:43:38
它不工作的原因是因为你没有引用正确的p.tiebreakfield
。您可以从input
转到.score
,next()
将带您转到p
:
$(this).parent(".score").next("p");
或者,您可以转到超级父级(父级的父级)并迭代回p
:
$(this).closest("div").find(".tiebreakfield");
你可以将你的代码简化为更小的方式,如下所示:
//find all text boxes which have a class that start with "score"; this will apply to score-n inputs
$('input[class^="score"]').keyup(function () {
//find the nearest p.tiebreakfield
var div = $(this).closest("div").find(".tiebreakfield");
//get an array of inputs
var inputs = $(this).parent().find("input[type=text]");
//first value of text box group
var value1 = parseInt(inputs[0].value);
//second value of text box group
var value2 = parseInt(inputs[1].value);
//your condition checking
var isShow = ["6,7", "7,6"].indexOf(value1 + "," + value2) !== -1;
if (isShow) {
//your actions
div.fadeIn();
} else {
//your actions again
div.fadeOut();
}
});
演示:http://jsfiddle.net/hungerpain/jQHDR/4/
我在您的代码中所做的更改:
ready
选择器,并使用了starts ready
selector of jQuery。div
变量<>H123在keyup触发输入中和周围获得了一个输入数组。(为了推广分数输入)以便它可以用于获取复杂if..else
循环的值later.
indexOf
进行了条件检查。如果条件不满足,它将返回-1
。发布于 2013-07-26 02:48:15
不需要2个ready()
.
div
.的
如果我很好地理解了您的问题,那么我认为这是您需要的代码示例:
$('.score1, .score2').keyup(function() {
var element = $(this).parent().siblings(".tiebreakfield");
var value1 = parseInt($(".score1").val());
var value2 = parseInt($(".score2").val());
if ((value1 == 6 || value1 == 7) && (value2 == 6 || value2 == 7) && (value1 !== value2)) {
element .fadeIn();
} else {
element .fadeOut();
}
});
演示:http://jsfiddle.net/vTQr6/
https://stackoverflow.com/questions/17866049
复制相似问题