我已經搜索並找到多個答案,簡單地說我的函數包裝在點擊處理程序中,儘管我希望它在頁面加載時運行,或者一旦我的JavaScript完成插入所有html。用點擊事件爲每個功能綁定活動?
我有一個動態創建的整個頁面。我正在使用此片段修復IE的佔位符。它確實有效,但不包含現場創建的元素。
$(document).ready(function(){
// Placeholder Fix for IE < 9
$("[placeholder]").each(function() {
var val = $(this).attr("placeholder");
if (this.value === "") {
this.value = val;
}
$(this).focus(function() {
if (this.value == val) {
this.value = "";
}
}).blur(function() {
if ($.trim(this.value) === "") {
this.value = val;
}
});
});
// Clear default placeholder values on form submit
$('form').submit(function() {
$(this).find("[placeholder]").each(function() {
if (this.value == $(this).attr("placeholder")) {
this.value = "";
}
});
});
});
我加入與JS表單元素,例如:
$('body').append('<input type="text" placeholder="placeholdertext" />');
有人能告訴我如何解決這個問題?
Shannon
當你說動態創建..你的意思是由服務器或JS?如果在for循環運行時目標元素還沒有在dom中,它顯然不會工作。如果你在JS中動態添加文本輸入,可以使用'$(中已經存在的',function(e){/ * stuff here * /} );' –
sambomartin
2013-04-22 00:08:53
無論何時使用'placeholder'屬性添加新元素,都需要爲這些新元素運行代碼。提供添加新元素的示例代碼 – charlietfl 2013-04-22 00:09:51
對模糊執行相同操作,並在創建時設置控件值。 'on'等同於'live' – sambomartin 2013-04-22 00:10:07