2016-08-05 49 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

没问题,很高兴帮助 –