2016-06-21 8 views
2

我申請jQuery的日期選擇到具有txt-date類的輸入元素,輸入:我如何可以訪問正被應用於日期選擇器

$('.txt-date').datepicker({ 
    showAnim: "blind", 
    changeMonth: true, 
    changeYear: true, 
    dateFormat: "dd.mm.yy", 
    numberOfMonths: 2 
}); 

正如你可以看到我指定顯示2個月。但這不是我想要的所有輸入字段的行爲。爲了使它更靈活,我想根據自定義屬性(如data-shown-months)的值確定numberOfMonths屬性的值。我試圖通過$(this)訪問輸入元素,像這樣

<input type="text" class="txt-date" data-shown-months="2"/> 

    $('.txt-date').datepicker({ 
    showAnim: "blind", 
    changeMonth: true, 
    changeYear: true, 
    dateFormat: "dd.mm.yy", 
    numberOfMonths: $(this).data('shown-months') 
}); 

但是沒有工作。我也試過$(this).attr('data-shown-months'),以確保它不是jquery data函數的問題。看來$(this)是指日期選擇器本身。至少它不涉及源輸入元素。你有什麼想法我將如何訪問源輸入元素?

回答

1

this指無論何時this是您撥打datepicker()時(可能爲window)。在對象參數中放置this不會更改其上下文。

更改爲:

$('.txt-date').datepicker({ 
    numberOfMonths: $('.txt-date').data('shown-months') //"this" is probably window 
}); 

如果您有相關的「TXT日期」類中的多個元素,每一個都有自己的「出月」的價值,你可以一個each()循環中初始化它們所有。在這種情況下,this將指向每個元素:

$('.txt-date').each(function() { 
    $(this).datepicker({ 
    numberOfMonths: $(this).data('shown-months') //"this" is the current element 
    }); 
}); 
+1

謝謝,@RIck。它真的把它整理出來了。從來沒有想過'這個'可以指窗口。 –

1

this總是指運行代碼的擁有者/呼叫者。由於您的代碼直接在頁面中運行,因此所有者是window對象。

如果你換你的代碼屬於一個事件你input,然後this將參照input,因爲它是事件的所有者:

$('.txt-date').one("focusin", function() { 
 
    $(this).datepicker({ 
 
    showAnim: "blind", 
 
    changeMonth: true, 
 
    changeYear: true, 
 
    dateFormat: "dd.mm.yy", 
 
    numberOfMonths: $(this).data("shown-months"), 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> 
 
<input type="text" class="txt-date" data-shown-months="1" value="1-month datepicker" /> 
 
<input type="text" class="txt-date" data-shown-months="2" value="2-months datepicker" />

從答案瑞克顯然更簡單,但我只是想解釋如何this的作品,以及如何使用它來實現你想要的。

相關問題