2012-01-13 52 views
0

我想在用戶鍵入輸入時動態創建url slug。不需要的字符應該被刪除。空格應該用連字符替代,一切都用小寫字母來代替。因此,如果用戶輸入「Ruddy's Cheese Shop」,則應該提供「ruddys-cheese-shop」。jquery - 動態生成url

這是我到目前爲止。

<input id="tb1" /> 
<div id="tb2"></div> 

$('#tb1').keyup(function() { 
    var Text = $('#tb1').val(); 
    Text = Text.toLowerCase(); 
    Text = Text.replace(/[^a-zA-Z0-9]+/g,'-'); 
    $('#tb2').html($('#tb1').val(Text)); 
}); 

它幾乎工程,但我是新來的JS。謝謝

+0

「這幾乎可以工作......「 - 你能更具體嗎? – 2012-01-13 18:11:36

+0

http://www.thewebsitetailor.com/jquery-slug-plugin/ – j08691 2012-01-13 18:14:27

回答

1

您的代碼略有改進。

$('#tb1').keyup(function() { 
    var text = $(this).val().toLowerCase(); 
    text = text.replace(/[^a-z0-9]+/g, '-'); 
    $('#tb2').text(text); 
}); 

你不需要一遍遍找$('#tb1')因素,因爲你必須在函數中有指向它作爲$(this)

http://jsfiddle.net/jFjR3/

0

它看起來不錯,除非你設置#tb2值。我想你想要:

$('#tb2').html(Text); 

當然,記得自從你調用toLowerCase,你不需要替換大寫字母。相反,更簡單的正則表達式:

Text = Text.replace(/[^a-z0-9]+/g,'-'); 

如果您還想要按照用戶類型更新編輯字段,這裏是一個完整的示例。請注意,它只會在您開始輸入時更新#td2。

<html> 
    <head> 
     <script src="js/jquery.js" ></script> 
     <script language="javascript"> 
     $(function() { 
     $('#tb1').keyup(function() { 
      var Text = $('#tb1').val(); 
      Text = Text.toLowerCase(); 
      Text = Text.replace(/[^a-z0-9]+/g,'-'); 
      $('#tb2').html(Text); 
      $('#tb1').val(Text); 
     }); 
     }); 
     </script> 
    </head> 
    <body> 
    <input type="text" id="tb1" value="Ruddy's Cheese Shop" /> 
    <div id="tb2"></div> 
    </body> 
    </html> 
0

看起來你需要運行一對夫婦的內容替換,即

Text = Text.replace(/[\s]+/g,'-'); 
Text = Text.replace(/[^a-z_0-9\-]+/g,''); 

那轉換紅潤的奶酪店,以ruddys芝士店

希望幫助