我正在尝试做一小段代码,它可以执行以下操作:我有很多组按钮加上一个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“,但我不知道该怎么做。
非常感谢您的回答!
它不正是我想要的,这是真棒。非常感谢! :) – Kishlin
没问题,很高兴帮助 –