2013-05-14 37 views
-1

我不是那麼習慣於使用jquery,所以任何幫助,將不勝感激。 我已經寫了這個功能,但不能讓它工作,誰能告訴我什麼是錯的。jquery函數來取代textarea文本不工作

$(function() { 
    $('#replace_button').onclick(function() { 
    $('#box_txt').val().replace(/\t/g, '[TAB]'); 
    $('#box_txt').val().replace(/\n/g, '[BREAK]'); 
    }); 
}); 

隨之而來是

<textarea name='box_txt' id='box_txt' rows='6' cols='50'></textarea> 
    <br> 
    <input type='button' id='replace_button' value='Replace'> 

我只是想替換[TAB]所有選項卡,然後用[BREAK]當按下按鈕的所有換行的HTML。

非常感謝。

回答

4

val返回一個字符串,而不是一種指向該值的指針。並且replace不會更改您傳遞的字符串(字符串在JavaScript中不可變),但會返回一個新字符串。

您可以使用

var field = $('#box_txt'), s = field.val(); 
s = s.replace(/\t/g, '[TAB]').replace(/\n/g, '[BREAK]'); 
field.val(s); 

Demonstration

+0

我只是這樣使用? ()函數(){('#replace_button')。onclick(function(){ var field = $('#box_txt'),s = field.val(); s = s.replace(/ \ t/g,'[TAB]')。replace(/ \ n/g,'[BREAK]'); field.val(s); }); }); – FoxyFish 2013-05-14 14:11:58

+0

@dystroy - nope,一個jquery對象沒有onclick()方法? – adeneo 2013-05-14 14:13:53

+0

是的,使用點擊,而不是點擊。 – 2013-05-14 14:14:23

0

是這樣的:

$(function() { 
     $('#replace_button').onclick(function() { 
     $('#box_txt').val($('#box_txt').val().replace(/\t/g, '[TAB]')); 
     $('#box_txt').val($('#box_txt').val().replace(/\n/g, '[BREAK]')); 
     }); 
    }); 

你得到的價值操縱它,但從來沒有把它背在textarea的:-)