2016-08-05 24 views
1

我正在嘗試做一小段代碼,它可以執行以下操作:我有很多組按鈕加上一個div,然後單擊按鈕向匹配的div添加預定義的文本。將預定義的html添加到帶按鈕的div

我把我的代碼如下的例子:https://jsfiddle.net/kdpqu98p/3/

HTML

<button id="hey-0">hey</button> 
<button id="hi-0">hi</button> 
<button id="hello-0">hello</button> 
<div id="text-0"></div> 

<button id="hey-1">hey</button> 
<button id="hi-1">hi</button> 
<button id="hello-1">hello</button> 
<div id="text-1"></div> 

<button id="hey-2">hey</button> 
<button id="hi-2">hi</button> 
<button id="hello-2">hello</button> 
<div id="text-2"></div> 

JAVASCRIPT

$(document).ready(function() { 

    // Loops through all 3 groups 
    for (var i = 2; i >= 0; i--) { 
    // Gets the buttons and text block for this group. 
    var text = '#text-' + i; 
    var hey = '#hey-' + i; 
    var hi = '#hi-' + i; 
    var hello = '#hello-' + i; 

    // Add functions to the buttons. 
    $(hey).click(function(e) { 
     $(text).append('hey'); 
    }); 

    $(hi).click(function(e) { 
     $(text).append('hi'); 
    }); 

    $(hello).click(function(e) { 
     $(text).append('hello'); 
    }); 
    } 

}); 

,我想它,但它總是添加文本它幾乎工程第一個div而不是對應於按鈕的那個,因爲......原因。 Oo

所以這裏是我的問題: 首先,爲什麼找到正確的按鈕工作,但不是爲div(因爲所有按鈕的工作,但它總是添加文本到第一個div)。 那麼,有沒有更簡單快捷的方法來做到這一點?我對JavaScript和jQuery很新,所以你必須對我說3歲。 我敢肯定,有一種方法可以擺脫循環,只使用一個函數,像「for all(#/ word/-/index /)」按鈕,使它們添加/ word /到html #text/index/div「,但我不知道該怎麼做。

非常感謝您的回答!

回答

4

通過使用DRY原則,您可以大量簡化代碼。首先在所有button元素上放置一個通用類,然後使用value屬性來存儲要放置在相關div中的值。從那裏你可以使用該類的單個事件處理程序,它可以找到相關的div並添加該值。試試這個:

$('.btn').click(function() { 
 
    $(this).nextAll('.text:first').append(this.value); 
 
});
div { 
 
    width: 300px; 
 
    height: 40px; 
 
    overflow-x: scroll; 
 
    margin-bottom: 10px; 
 
    background-color: #efefef; 
 
    border: 1px solid black; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="btn" value="hey-0">hey</button> 
 
<button class="btn" value="hi-0">hi</button> 
 
<button class="btn" value="hello-0">hello</button> 
 
<div class="text"></div> 
 

 
<button class="btn" value="hey-1">hey</button> 
 
<button class="btn" value="hi-1">hi</button> 
 
<button class="btn" value="hello-1">hello</button> 
 
<div class="text"></div> 
 

 
<button class="btn" value="hey-2">hey</button> 
 
<button class="btn" value="hi-2">hi</button> 
 
<button class="btn" value="hello-2">hello</button> 
 
<div class="text"></div>

+0

它不正是我想要的,這是真棒。非常感謝! :) – Kishlin

+0

沒問題,很高興幫助 –

相關問題