我怎样才能改变这与jquery?
问题描述:
我想更改搜索框中的文本值,例如说“Awesome Search”。我知道可以用Jquery完成,但我无法实现它的工作。你能帮忙吗?我怎样才能改变这与jquery?
请注意,这是由WordPress提供的默认设置,对于我来说,要编辑文件以将内容与行为分开是很困难的,所以我需要Jquery覆盖默认设置。迄今为止提供的两个答案似乎并没有这样做。
<input type="text"
onblur="if (this.value == '') {this.value = 'To search, type and hit enter';}"
onfocus="if (this.value == 'To search, type and hit enter') {this.value = '';}"
id="s"
name="s"
value="To search, type and hit enter"
class="text_input">
答
因此,看来你只是要替换的文本框的默认值在页面加载时,无需修改HTML,因此使用jQuery ...
$(function() {
$('#s').val('Awesome Search');
});
答
输入:
<input type="text" id="s" name="s" value="To search, type and hit enter" class="text_input">
而jQuery的:
$('#s').focus(function() {
if ($(this).text() == 'To search, type and hit enter'){
$(this).text('');
}
}
$('#s').blur(function() {
if (strlen($.trim($(this).text())) == 0){
$(this).text('To search, type and hit enter');
}
}
+0
问题在于,我在OP中粘贴的代码是使用Wordpress设置的默认代码,因此对于我来说很难重新组织所有内容。有没有一种方法可以用jquery替换wordpress提供的“Awesome search”的默认文本? – mjmitche 2011-06-07 03:27:36
答
首先,因为你是使用jQuery:让你的代码,你的标记。在身体
<input type="text"
id="s"
name="s"
value="To search, type and hit enter"
class="text_input" />
然后,你需要绑定到你的表单提交
<script type="text/javascript">
$(function() {
var s = $('#s');
s.blur(function() {
if (s.val() === '') {
s.val('To search, type and hit enter');
}
}).focus(function() {
if (s.val() === 'To search, type and hit enter') {
s.val('');
}
});
});
</script>
然后:把这个文档的头部。你正在做一个Ajax电话吗?它看起来沿着线:
$('#theFormId').submit(function(e) {
e.preventDefault();
// do your ajax stuff.
// in the callback:
$('#s').val('Awesome Search.');
});
*当你想让它显示“Awesome Search”时? – 2011-06-07 02:28:33
@ Box9哎呀。抱歉。我希望文本在搜索框中可见,而访问者不必将光标移动到搜索框中。 – mjmitche 2011-06-07 03:25:24