찾은 요소가 없을 때 기능이 실행되는 이유는 무엇입니까?
-
10-07-2019 - |
문제
그러나 다음 코드가 있습니다 input.formdate
여전히 실행될 것입니다 getDateFormat
기능. 이것은 나에게 의미가 없습니다.
그 이유를 아는 사람이 있습니까?
$(function() {
$("input.formdate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: getDateFormat()
});
});
function getDateFormat()
{
var format = 'DMY';
if (document.edit_form && document.edit_form.date_format)
format = document.edit_form.date_format.value;
if (format = "DMY")
return "dd-mm-yy";
else
return "mm-dd-yy";
}
해결책
getDateFormat 함수는 JavaScript가 객체 문자 그럴 표기법에 있으므로 구문 분석하자마자 실행됩니다.
당신의 표현은 다음과 같이 평가됩니다
$(function() {
$("input.formdate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: <RESULT_FROM_CALLING_getDateFormat()>
});
});
다른 팁
오래된 답변 :
(질문의 잘못 이해 - 의견 참조)
기능을 호출하고 결과를 전달하기 때문에 수행해야 할 작업 대신 기능에 대한 참조를 전달합니다 (즉, 변수로 취급).
이 작업을 수행:
$(function() {
$("input.formdate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: getDateFormat
});
});
업데이트:
jQuery UI DatePicker API를 확인한 후에는 문자열을 dateformat로 전달해야합니다.
FormDate 클래스에 적어도 하나의 입력이 없으면 기능을 실행하는 것을 원하지 않으면 다음을 수행해야합니다.
if ( $('input.formdate').length > 0 )
{
$("input.formdate").datepicker
(
{ changeMonth: true
, changeYear: true
, dateFormat: getDateFormat()
}
);
}
또는 If : 인라인으로 수행 할 수 있습니다.
$("input.formdate").datepicker
(
{ changeMonth: true
, changeYear: true
, dateFormat:
$('input.formdate').length > 0 ? getDateFormat() : 'dd-mm-yy'
}
);
그것이 다소 읽기 쉬운 경우 논쟁의 여지가 있습니다.
(아마도 그보다 더 짧은 길이있을 것입니다. 그러나 지금 가야합니다.)
제휴하지 않습니다 StackOverflow