2 回答
TA贡献1921条经验 获得超9个赞
您要替换.data附加了事件处理程序的元素。
如果你只是写入<p>而不是重写整个 DIV 会更好。
var data = [{
"content": "first content"
},
{
"content": "second content"
}
];
$('.data').click(function() {
var datacontent = $(this).data('content');
//alert (datacontent)
$(this).siblings("p").text(data[datacontent].content)
});
.data {
background: tomato;
color: white;
padding: 8px;
display: inline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<p>
Hi, Please click data
</p>
<div class="data" data-content="0">data 1</div>
<div class="data" data-content="1">data 2</div>
</div>
TA贡献1863条经验 获得超2个赞
请尝试
var data = [{
"content": "first content"
},
{
"content": "second content"
}
];
//$('.data').click(function() {
$(document).on('click','.data', function(){
var datacontent = $(this).attr('data-content');
//alert (datacontent)
$(this).parent().html('').append(`
<div class="wrap">
<p>${data[datacontent].content}</p>
<div class="data" data-content="0">data 1</div>
<div class="data" data-content="1">data 2</div>
</div>
`)
});
TA贡献1906条经验 获得超10个赞
您不需要替换整个 html 代码,只需替换同级p标签即可。
var data = [{
"content": "first content"
},
{
"content": "second content"
}
];
$('.data').on('click', function(e) {
var datacontent = $(this).attr('data-content');
$(this).siblings("p").html(data[datacontent].content)
});
.data {
background: tomato;
color: white;
padding: 8px;
display: inline;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
<p>
Hi, Please click data
</p>
<div class="data" data-content="0">data 1</div>
<div class="data" data-content="1">data 2</div>
</div>
添加回答
举报