为什么这部分 jQuery 不能正常工作?
$(function() {
if ($('#slide-01').is(":first-child")) {
$('input:radio[id=target-slide-01]').prop('checked', true);
} else {
$('input:radio[id=target-slide-01]').prop('checked', false);
}
if ($('#slide-02').is(":first-child")) {
$('input:radio[id=target-slide-02]').prop('checked', true);
} else {
$('input:radio[id=target-slide-02]').prop('checked', false);
}
if ($('#slide-03').is(":first-child")) {
$('input:radio[id=target-slide-03]').prop('checked', true);
} else {
$('input:radio[id=target-slide-03]').prop('checked', false);
}
if ($('#slide-04').is(":first-child")) {
$('input:radio[id=target-slide-04]').prop('checked', true);
} else {
$('input:radio[id=target-slide-04]').prop('checked', false);
}
});
执行 jQuery 的链接位于此 jsFiddle 上.
当我检查 HTML 和 CSS 中的元素时,每张幻灯片最终都有“:first-child”(随着幻灯片旋转),但我猜测是 jQuery 无法识别旋转或者我的 jQuery 在某处关闭了。
我也尝试过使用 :first 代替 :first-child,但这并没有什么不同。
最佳答案
单选按钮的函数只在页面加载时被调用一次,因为它是一个匿名的自调用函数。如果你给个名字
function updateRadioButtons() {
if ($('#slide-01').is(":first-child")) {
$('input:radio[id=target-slide-01]').prop('checked', true);
} else {
$('input:radio[id=target-slide-01]').prop('checked', false);
}
if ($('#slide-02').is(":first-child")) {
$('input:radio[id=target-slide-02]').prop('checked', true);
} else {
$('input:radio[id=target-slide-02]').prop('checked', false);
}
if ($('#slide-03').is(":first-child")) {
$('input:radio[id=target-slide-03]').prop('checked', true);
} else {
$('input:radio[id=target-slide-03]').prop('checked', false);
}
if ($('#slide-04').is(":first-child")) {
$('input:radio[id=target-slide-04]').prop('checked', true);
} else {
$('input:radio[id=target-slide-04]').prop('checked', false);
}
}
你可以在你的幻灯片改变时调用它
function moveLeft() {
$('#myslider ul').animate({
left: +containerWidth
}, 600, function () {
$('#myslider ul > li:last-child').insertBefore('#myslider ul > li:first-child');
$(this).css('left', '');
updateRadioButtons();
});
}
function moveRight() {
$('#myslider ul').animate({
left: -containerWidth
}, 600, function () {
$('#myslider ul > li:first-child').insertAfter('#myslider ul > li:last-child');
$(this).css('left', '');
updateRadioButtons();
});
}
还有页面加载
$(function() {
// Key animation.
updateRadioButtons();
var myTimer = setInterval(function () {
moveRight();
}, 5000);
关于jquery - 为什么是:first-child not working?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26588703/