假设您有 10-15 个固定的 divs
您想要animate()
具有不同的参数。使用 jQuery,为每个 div 传递不同参数的最佳方法是什么?我当前的方法(如下)尝试通过 id
function
中的文本。这是第一步,最终我想我会通过 animation()
duration
和rotation
如function
parameters
(例如 float(ID, duration, rotation)
现在返回以下内容: Error: Syntax error, unrecognized expression: "#candy"
$(document).ready(function () {
float("candy");
float("candy2");
//etc
});
function float(ID) {
let id = "#" + ID;
$('"' + id + '"').animate({
top: 100,
}, 5000 );
};
最佳答案
您根本不需要声明作用域变量。只需将函数调用的参数传递给方法即可。
$(document).ready(function () {
float("candy", 5000);
float("candy2", 2000);
});
function float(ID, duration) {
$('#' + ID).animate({
top: 100,
}, duration );
};
#candy {
background-color: red;
width: 200px;
height: 200px;
position: relative;
}
#candy2 {
background-color: yellow;
width: 200px;
height: 200px;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div id="candy"></div>
<div id="candy2"></div>
</div>
关于javascript - jQuery 将函数参数或变量添加到 id 选择器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59938153/