我的<li>
、data-author
和data-body
上有以下的data-author
类型。
单击li
时,我希望将data-author
和data-info
附加到几个div
类中,例如classOne
和classTwo
。
单击data-
并将数据传递到所需位置的最佳方法是什么?
代码:
$(document).ready(function() {
var url = "assets/js/data.json",
fetchJSON = $.getJSON(url);
fetchJSON.done(function(response) {
var buttons = response.map(function(i) {
return $('<li>').html(i.title).attr({
"data-author": i.author,
"data-body": i.body
})
});
$('ul').append(buttons);
});
$('ul').on('click', 'li', function(){
});
}); //Ready function closed
发布于 2015-01-09 05:29:46
只需从data-...
元素中获取this
属性即可。
$('ul').on('click', 'li', function(){
var $this = $(this);
var author = $this.attr("data-author");
var body = $this.attr("data-body");
$('div.classOne').text(author);
$('div.classTwo').text(body);
});
注意,即使使用较短的代码,也可以生成列表:
var buttons = response.map(function(i) {
return $('<li>', {
text: i.title,
"data-author": i.author,
"data-body": i.body
})
});
如果您想在DOM中添加属性,请不要使用data()
,因为这样会将它们存储在dom元素中。否则,您可以使用它,并且这些字段可以由$this.data("author")
和$this.data("body")
访问。
var response = [
{ title: "Hello World!", author: "Someone", body: "Hi there!" },
{ title: "Hello Mars!", author: "Another One", body: "Greetings!" }
];
var buttons = response.map(function(i) {
return $('<li>', {
text: i.title,
"data-author": i.author,
"data-body": i.body
})
});
$("ul").html(buttons);
$('ul').on('click', 'li', function(){
var $this = $(this);
var author = $this.attr("data-author");
var body = $this.attr("data-body");
$('div.author').text(author);
$('div.body').text(body);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
<div class="author"></div>
<div class="body"></div>
发布于 2015-01-09 05:31:10
尝尝这个,
$('ul').on('click', 'li', function(){
$('div.classOne').html($(this).data('author'));
$('div.classTwo').html($(this).data('body'));
});
$('ul').on('click', 'li', function() {
$('div.classOne').html($(this).data('author'));
$('div.classTwo').html($(this).data('body'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li data-author="Rohan" data-body="Lorem ipsum doner inut">List 1</li>
<li data-author="Andrew" data-body="Oh, Again Lorem ipsum doner inut">List 2</li>
</ul>
<div class="classOne"></div>
<div class="classTwo"></div>
https://stackoverflow.com/questions/27854355
复制相似问题