2014-11-17 86 views
0

我有一個文本框,它包含一個值爲「你好」。我有另一個按鈕,當我點擊一個按鈕時,文本應該改爲「不是你好」,如果我再次點擊它應該改爲「不打招呼」,並且這個過程正在進行中..或者,不應該添加否,我沒有成功做到這一點。按鈕單擊替換文本

請檢查我的代碼

$('#negate a').click(function(e) { 
    e.preventDefault(); 
    var opinionWord = $('input[name="opinion-word"]').val(); 
    if (/no/i.test(opinionWord)) { 
     opinionWord = opinionWord.replace('no ',''); 
     opinionword = opinionWord.substr(opinionWord.indexOf(" ") + 1); 
     alert('f'); 
     $('input[name="opinion-word"]').val("not "+opinionWord); 
    } 
    else { 
     opinionWord = opinionWord.replace('not ',''); 
     opinionword = opinionWord.substr(opinionWord.indexOf(" ") + 1); 
     alert(opinionword); 
     $('input[name="opinion-word"]').val("no "+opinionWord); 
    } 
}); 
+0

添加代碼的jsfiddle和共享 –

回答

0

你的代碼是好的,你就忘了not是包括字母no。所以之前剛剛檢查了not

$('#negate a').click(function(e) { 
    e.preventDefault(); 
    var opinionWord = $('input[name="opinion-word"]').val(); 
    if (/not/i.test(opinionWord)) { 
     opinionWord = opinionWord.replace('not ',''); 
     opinionword = opinionWord.substr(opinionWord.indexOf(" ") + 1); 
     alert('f'); 
     $('input[name="opinion-word"]').val("no "+opinionWord); 
    } 
    else { 
     opinionWord = opinionWord.replace('no ',''); 
     opinionword = opinionWord.substr(opinionWord.indexOf(" ") + 1); 
     alert(opinionword); 
     $('input[name="opinion-word"]').val("not "+opinionWord); 
    } 
}); 

這裏是工作提琴http://fiddle.jshell.net/5p8c31Lc/

+0

正確,邏輯錯誤發生感謝 – aniltc