作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一小段代码来执行以下操作:我有许多按钮组和一个 div,单击这些按钮会将预定义的文本添加到匹配的 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 而不是与按钮对应的 div,因为...原因。哦
所以这是我的问题:首先,为什么找到正确的按钮有效,但对 div 无效(因为所有按钮都有效,但它总是将文本添加到第一个 div)。那么,有没有更简单快捷的方法呢?我是 javascript 和 jquery 的新手,所以你必须像对我 3 岁的 child 一样说话。我确定有一种方法可以摆脱循环并只使用一个函数,该函数会说“对于所有(#/word/-/index/)按钮,让它们将/word/添加到 html #text-/index/div"但我不知道该怎么做。
非常感谢您的回答!
最佳答案
您可以使用 DRY 原则极大地简化您的代码。首先在所有的button
元素上放置一个公共(public)类,并使用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>
关于javascript - 将预定义的 html 添加到带有按钮的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38791891/
我是一名优秀的程序员,十分优秀!