我有以下data
我的类型<li>
data-author
和data-body
。
当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
只需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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句