【发布时间】:2018-03-12 14:30:14
【问题描述】:
我正在尝试使用 jquery 在其他 div 中添加单击元素数据文本。
它的运行逻辑应该如下:
当你点击 word1 时,这个点击的 word1 应该在添加 word1 之后进入 #words div 如果你想添加 word2 然后点击 word2 它应该也进入 #words div。
我的问题是我无法添加第二个点击的单词。
这是来自 jsfiddle 的 DEMO。
$("body").on("click", ".word", function() {
var dataWord = $(this).attr("data-word");
var dataBox = $("#words");
var oldWords = $(dataBox).html("<div class='ab'>"+dataWord+"</div>");
$(dataBox).html(oldWords.html() + oldWords.html());
return false;
});
html, body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
background-color: #FAFAFA;
font-family: 'Helvetica Neue', helvetica, arial, sans-serif;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
-ms-text-size-adjust: 100%;
-webkit-texts-size-adjust: 100%;
-webkit-backface-visibility: hidden;
}
.container {
position:relative;
width:100%;
max-width:400px;
margin:0px auto;
padding:50px 0px;
overflow:hidden;
}
.word {
position:relative;
background-color:red;
border-radius:2px;
margin-left:5px;
color:#ffffff;
float:left;
font-weight:400;
font-size:13px;
padding:5px;
cursor:pointer;
}
.word:hover {
background-color:black;
color:#ffffff;
}
.addedWords {
position:relative;
float:left;
width:100%;
padding:10px;
background-color:#d8dbdf;
margin-top:40px;
}
.ab {
background-color:blue;
color:#ffffff;
margin-left:5px;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="word" data-word="word1">
Word1
</div>
<div class="word" data-word="word2">
Word 2
</div>
<div class="addedWords" id="words">
</div>
</div>
【问题讨论】:
-
是否要在点击每个文本时附加相应的数据?
标签: javascript jquery html