我想要 10 个 div,当有人点击它们中的每一个或将鼠标悬停在其中任何一个时,它都会发生变化。我现在拥有的是来自 php 的 foreach(遍历我想显示的东西的数组)并以类似的方式为每个写一个脚本,唯一的区别是 div 的 id:
<?php
foreach($lines as $line) {
$lineId = $line->getId();
echo "$('#translation$lineId').hover(
function() { $('#translation$lineId').css('background-color', 'yellow'); },
function() { $('#translation$lineId').css('background-color', 'transparent'); });";
echo "$('#translation$lineId').focusin(function()
{ $('#translation$lineId').css('background-color', 'red'); });";
echo "$('#translation$lineId').focusout(function()
{ $('#translation$lineId').css('background-color', 'transparent'); });";
}
?>
在浏览器中,当 $lines 的数量很大时,它可以达到数百行代码。 有没有更好的办法?我想为此使用 JQuery。
另一个奖励问题是我如何在 Jquery 中做到当有人点击一个 div 时它使它变红,当有人取消点击它(点击其他地方)时它再次变得透明。这有点像我在我的代码中试图做的。 Jquery 也在这里。
最佳答案
为什么不使用类呢?
标记:
<div id="div1" class="mydivclass">Something</div>
<div id="div2" class="mydivclass">Something Else</div>
脚本:
$(document).ready(function() {
$('.mydivclass').click(function() {
$(this).doSomething();
});
});
奖金问题当你点击它时使 div 变红,当你点击其他地方时变透明......
$(document).ready(function() {
$('html').click(function(event) {
$('.mydivclass').each(function() {
if ($(event.target).closest(this).length) {
$(this).css('background-color','red');
}
else {
$(this).css('background-color','rgba(0,0,0,0)');
}
});
});
});
悬停只需使用 :hover
css 伪类
.mydivclass {
background-color:rgba(0,0,0,0);
}
.mydivclass:hover {
background-color:red;
}
关于php - jQuery 将相同的功能应用于不同的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8605569/