因此,对于输入(或其他类型的el)的默认文本交换,我有这个片段
<input class="js_text_swap" type="text" value="Enter your email" />
if($('.js_text_swap').length > 0) { $('.js_text_swap').each(function() { var that = $(this), value = that.val(); // remembering the default value that.focusin(function() { if(that.val() === value) { that.val(''); } }); that.focusout(function() { if(that.val() === '') { that.val(value); } }); }); }
所以我的问题是:
1)有人有更好的解决方案吗?
2)有没有人知道如何使用实时添加的元素(在页面加载后用js添加)?
由于
答案 0 :(得分:1)
日版!
<强> HTML 强>
<input placeholder="Click..." class="text" type="text">
<强> CSS 强>
.text{color:#aaa}
.text.focus{color:#444}
<强> JS 强>
$("input[placeholder]").each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
http://yckart.com/jquery-simple-placeholder/
<强>更新强>
要使其与ajax或类似工具一起使用,您需要将其转换为“插件”并在成功的ajax请求之后(或在动态废话创建之后)调用它。
这样的事情(非常简单的例子):
jQuery.fn.placeholder = function() {
return this.each(function() {
var placeholder = $(this).attr("placeholder");
$(this).val(placeholder).focus(function() {
if ($(this).val() == placeholder) {
$(this).val("").addClass('focus');
}
}).blur(function() {
if ($(this).val() === "") {
$(this).val(placeholder).removeClass('focus');
}
});
});
};
$("input:text, textarea").placeholder();
$("button").on("click", function() {
$(this).before('<input type="text" placeholder="default value" />');
$("input:text, textarea").placeholder();
});