你是非常正確的,它不適用於委託。這很可能是由於reasons given here,但這只是一個猜測。以下是一些建議的解決方法。
沒有jQuery的
您可以使用事件,而不是捕捉事件冒泡爲discussed in this blog entry(如使用IE支持見下文警告)的,使這項工作。
用下面的HTML ...
<p id='parent'>
Enter some values:<br/>
<input type='text' id='requiredValue'/>
<input type='text'/>
</p>
<div id='output'>
</div>
...這個JavaScript顯示卡在正確的位置的事件。
var outputDiv = document.getElementById('output'),
parentDiv = document.getElementById('parent'),
inputDiv = document.getElementById('requiredValue');
parentDiv.addEventListener('focus', function() {
outputDiv.innerHTML = outputDiv.innerHTML + "<p>parent</p>";
}, true);
inputDiv.addEventListener('focus', function() {
outputDiv.innerHTML = outputDiv.innerHTML + "<p>input</p>";
}, true);
使這項工作與IE
事件俘獲不能在IE上面我們提到的博客然而工作可以看出,IE支持的focusIn和事件的內容,你想要什麼裏面做的事件。
這意味着,與另外兩個事件處理程序,那麼你可以在所有的情況下,處理這種情況:
parentDiv.onfocusin = function() {
outputDiv.innerHTML = outputDiv.innerHTML + "<p>parent</p>";
};
inputDiv.onfocusout = function() {
outputDiv.innerHTML = outputDiv.innerHTML + "<p>input</p>";
};
使用最新版本的jQuery
此功能的工作原理與使用預期'on'功能。
。on(events [,selector] [,data],handler(eventObject))
在'on'的函數參數中指定選擇器意味着'on'使用事件委託。從文檔:
當提供選擇器時,事件處理程序稱爲委託。當事件直接發生在綁定元素上時,不會調用該處理程序,而只會爲與選擇器匹配的後代(內部元素)調用該處理程序。 jQuery將事件從事件目標引發到處理程序所附的元素(即,最內層到最外層的元素),並沿着匹配選擇器的路徑上的任何元素運行處理程序。
對於下面的HTML
<p id='parent'>
Enter some values:<br/>
<input type='text' class='requiredValue'/>
<input type='text'/>
</p>
下面的JavaScript代碼按預期工作
$(document).ready(function() {
var initialText = "Enter a value";
$('.requiredValue').val(initialText);
$('#parent').on('focus', '.requiredValue', function() {
var contents = $(this).val();
if (contents === initialText) {
$(this).val("");
}
});
$('#parent').on('blur', '.requiredValue', function() {
var contents = $(this).val();
if (contents.length == 0) {
$(this).val(initialText);
}
});
});
HTML 5技術
一個更好的技術,它是HTML 5標準can be found here。從博客:
<input type="text" name="first_name" placeholder="Your first name...">
你會發現,所有你需要做的就是添加一個佔位符屬性與您所選擇的通用文本。很高興你不需要JavaScript來創建這種效果,是吧?
由於佔位符是一個新功能,它在用戶的瀏覽器檢查的支持是很重要的:
function hasPlaceholderSupport() {
var input = document.createElement('input');
return ('placeholder' in input);
}
如果用戶的瀏覽器不支持佔位符的功能,您將需要使用
/* mootools ftw! */
var firstNameBox = $('first_name'),
message = firstNameBox.get('placeholder');
firstNameBox.addEvents({
focus: function() {
if(firstNameBox.value == message) { searchBox.value = ''; }
},
blur: function() {
if(firstNameBox.value == '') { searchBox.value = message; }
}
});
是'#表單container'靜態元素:通過MooTools,道場,或您所選擇的JavaScript工具包回退?你不能使用佔位符屬性嗎? – undefined
@undefined - 是的,forms-container是一個靜態元素。我無法使用placeholder屬性,因爲它在舊版瀏覽器中不受支持,我無法使用模擬它們的jquery插件。 – toofast1227
@toofast我已經更新了我的答案。看看這是否適合你。 – MikeD