我正在尝试使用我使用jquery生成的具有预定值的div进行引用,但似乎找不到合适的方法。
我尝试使用.find()和.attr()方法无济于事。我觉得这与范围有关,但我很茫然。
我正在尝试根据相邻的div(.cube)的行和列值进行更改。我的警报脚本不断返回未定义的结果。
<div class="cube" id="1" row="1" col="1"></div>
<div class="cube" id="2" row="1" col="2"></div>
<div class="cube" id="3" row="1" col="3"></div>
<div class="cube" id="4" row="1" col="4"></div>
$(".cube").each(function() {
var adjacentrowplus = +$(this).attr('row') + 1;
var adjacentcolplus = +$(this).attr('col') + 1;
var adjacentrowminus = +$(this).attr('row') - 1;
var adjacentcolminus = +$(this).attr('col') - 1;
if ($(".cube").attr("row") == adjacentrowplus) {
console.log("the div equals the row");
} else {
console.log("the div doesnt equal the row");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cube" id="1" row="1" col="1"></div>
<div class="cube" id="2" row="1" col="2"></div>
<div class="cube" id="3" row="1" col="3"></div>
<div class="cube" id="4" row="1" col="4"></div>
答案 0 :(得分:2)
您的逻辑有些偏离。如果您将if
语句视为伪代码,我们将看到它永远不会返回true
:
仅第一次迭代:
if 1 == 1 + 1 then print "the div equals the row"
如您所见,在row
的值上加一个,然后与row
的值进行比较是没有道理的。
请对照row
属性检查递增的id
值。
此外,您正在对照$(".cube").attr("row")
进行检查,该检查将始终仅检查第一个。如果这有意义,我将更改答案以反映这一点。但是,我假设您想检查当前正在迭代的.cube
。
编辑:要适应更新的目标,请执行以下操作:识别相邻元素
然后,这将变得更容易解决。根据以下问题提供的结构,您将找到一个jQuery版本和直接的JavaScript解决方案:
let id = 2;
function findNeighborsJQ(id) {
console.log('With jQuery:');
console.log('Prev cube: ', $('#'+id).prev('div.cube').attr('id'));
console.log('Next cube: ', $('#'+id).next('div.cube').attr('id'));
}
function findNeighbors(id) {
console.log('Without jQuery:');
console.log('Prev cube: ', document.getElementById(id).previousElementSibling.id);
console.log('Next cube: ', document.getElementById(id).nextElementSibling.id);
}
console.log('Given and id of "'+id+'"...');
findNeighborsJQ(id);
findNeighbors(id);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cube" id="1" row="1" col="1"></div>
<div class="cube" id="2" row="1" col="2"></div>
<div class="cube" id="3" row="1" col="3"></div>
<div class="cube" id="4" row="1" col="4"></div>