2009-10-01 58 views
1

我有一個有兩個輸入字段和標籤雲的表單。如何保持jquery函數覆蓋一個輸入字段與onclick寫入第二個輸入?

我想要用戶把焦點放在第一個輸入,然後單擊一個標籤,從而觸發一個jquery函數,將點擊標籤放在第一個輸入中。然後,用戶關注第二個輸入,單擊一個觸發類似jQuery功能的標記,將第二個標記放入第二個輸入字段。

我的代碼用於將第一個標籤放在第一個輸入中,但當單擊第二個標籤時,該點擊標籤會放入兩個輸入字段。

我懷疑我需要幫助$(this).html或綁定。我很清楚$('a')。click函數發生了兩次,最新值爲$(this).html()。

如何隔離這兩個函數,以便將第一個標記寫入第一個輸入,並將第二個標記寫入第二個輸入?

以下是我已經寫了我的HTML和jQuery:

形式:

<div id="content"> 
     <h3 class="replaceTag">Replace A Tag</h3> 
    <p class="showToReplace">Replace 
      <input class="inputToReplace" type="text" name="" value=""> 
      With 
      <input class="inputWithReplace" type="text" name="" value=""> 
      <input type="button" name="" value="Go"> 
    </p> 

標籤雲的結構,只顯示 「A」 爲簡潔。

<div id="tagReference"> 
    <div class="tagWindow"> 

     <h4 class="alphaLetter">A</h4> 

      <div id="alphachunk"> 
       <a class="_tag_suggestion">access, </a> 
       <a class="_tag_suggestion">accessibility,</a> 
       <a class="_tag_suggestion">accountant, </a> 
       <a class="_tag_suggestion">acoustical,</a> 

      </div> 

     <h4 class="alphaLetter>B</h4> 
       <div id="alphachunk"> 
        <!--and so on for the alphabet--> 
       </div> 
     </div> 
    </div> 

這裏面有一個標籤存在字母表中的每個字母。

這裏是jQuery的

$(document).ready(function(){ 
    $('.inputToReplace').focus(function(){ 
    $("a").click(function(){ 
     $('.inputToReplace').val($(this).html()); 
    }); 
    }); 

$('.inputWithReplace').focus(function(){ 
     $("a").click(function(){ 
     $('.inputWithReplace').val($(this).html()); 
      }); 
    }); 
}); 

現在,一個可愛的屏幕截圖。 alt text http://www.kevtrout.com/stackoverflowimages/editTagsScrn.png

回答

0

jQuery允許您綁定多個單擊事件處理程序。您需要添加第二個之前解除綁定使用.unbind以前的單擊事件處理程序(或兩者會火,因爲你有經驗):

$("a").unbind("click"); 

所以,你的代碼能讀:

$('.inputWithReplace').focus(function(){ 
    $("a").unbind("click").click(function(){ 
    $('.inputWithReplace').val($(this).html()); 
     }); 
}); 
+0

20分鐘寫愚蠢的問題,1分鐘,得到答案。我愛你stackoverflow。謝謝克里斯。 – kevtrout 2009-10-01 21:50:13

0

你可以縮短你的代碼

$(document).ready(function(){ 
    $('input:text').focus(function(e){ 
     tagSelector(e.target); 
    }); 
}); 

function tagSelector(elem) { 
    $("a").unbind('click').click(function(e){ 
    $(elem).val($(e.target).text()); 
    }); 
} 

您可能需要使用更具體的選擇的輸入,我會離開,作爲一個練習你來決定:)

編輯:

甚至這個

$(function(){ 
    $('input:text').focus(tagSelector); 
}); 

function tagSelector(e) { 
    $("a").unbind('click').click(function(){ 
    $(e.target).val($(this).text()); 
    }); 
} 
+0

是的,錨點有一個我用作選擇器的類。我刪除了它以保持示例清晰。與輸入上的名稱相同。 – kevtrout 2009-10-02 14:03:37

相關問題