2011-06-07 122 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