2011-06-07 132 views
0

我想更改搜索框中的文本值,例如说“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"> 
+2

*当你想让它显示“Awesome Search”时? – 2011-06-07 02:28:33

+0

@ Box9哎呀。抱歉。我希望文本在搜索框中可见,而访问者不必将光标移动到搜索框中。 – mjmitche 2011-06-07 03:25:24

回答

1

因此,看来你只是要替换的文本框的默认值在页面加载时,无需修改HTML,因此使用jQuery ...

$(function() { 
    $('#s').val('Awesome Search'); 
}); 
0

输入:

<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

1

首先,因为你是使用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.'); 
}); 
+0

问题在于,我在OP中粘贴的代码是使用Wordpress设置的默认代码,所以对于我来说重新组织一切都很困难。有没有办法来替换WordPress提供的默认文本? – mjmitche 2011-06-07 03:26:45

+0

即我正试图说我必须重写默认值,但我不认为你的代码这样做。 – mjmitche 2011-06-07 03:30:44