[英]get value of sibling in same div
I would like to do a certain kind of logic for every item with a given class (the code is reused that why i dont work with id): the items are within the same div everywhere: 我想对具有给定类的每个项目执行某种逻辑(代码被重用,这就是为什么我不使用id的原因):这些项目在每个地方都在同一个div中:
<div id="mDiv>
<input type="text" class = "class1>
<input type="hidden"/>
</div>
and the script is something like that: 脚本是这样的:
$(".class1").val(calcDefaultDate())
function calcDefaultDate(){
var currDate = $(this).siblings('input[type=hidden]').val();
if (currDate == "") {
return new Date();
}
return currDate;
}
The problem is that this way the $(this) is the Window instead of the element with class1, I am quite new to javascript so it might be something really easy but how should it be handled? 问题是这样,$(this)是Window而不是class1的元素,我对javascript很陌生,所以它可能确实很简单,但应如何处理?
Thanks! 谢谢!
You can try to give the element as an argument instead of trying to reach it with the this
keyword: 您可以尝试将元素作为参数,而不是尝试使用this
关键字来实现:
$(".class1").val(calcDefaultDate($(".class1")))
function calcDefaultDate($element){
var currDate = element.siblings('input[type=hidden]').val();
if (currDate == "") {
return new Date();
}
return currDate;
}
By the way, maybe you would prefer return new Date(+currDate);
顺便说一句,也许您希望return new Date(+currDate);
instead of return currDate;
而不是return currDate;
, this way the type of what your function returns is more consistent. ,这样您的函数返回的类型就更加一致。
Try passing the div as an argument to your function: 尝试将div作为参数传递给函数:
$(".class1").each(function() {
$(this).val(calcDefaultDate($(this)));
});
function calcDefaultDate(el) {
var currDate = $(el).siblings('input[type=hidden]').val();
if (currDate == "") {
return new Date();
}
return currDate;
}
Or apply the function to each element: 或将函数应用于每个元素:
$(".class1").each(function() {
updateDefaultDate($(this));
});
function updateDefaultDate(el) {
var currDate = $(el).siblings('input[type=hidden]').val();
if (currDate == "") {
currDate = new Date();
}
el.val(currDate);
}
Or pass all the elements to your function: 或将所有元素传递给函数:
updateDefaultDate($(".class1"));
function updateDefaultDate(elements) {
$(elements).each(function() {
var currDate = $(this).siblings('input[type=hidden]').val();
if (currDate == "") {
currDate = new Date();
}
$(this).val(currDate);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.