我有一个列表,里面只有国家标志、国家名称和国家代码,实际上我是从JSON 派生的
我写了一个循环来呈现像这样的html元素
data =
[
{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}]
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div id="listSection">'+
'<div style="display:flex">'+
'<div id="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div id="nameSection">' + countryName + '</div>' +' '+
'<div id="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
我还有一个divs部分
<div id="inputSection"> </div>
<div id="countries-list">
</div>
我已经做了类似的事情,当你点击输入部分时,列表就会出现,我可以从列表中选择,我只需要ONLY标志应该显示
<script type="text/javascript">
$(document).ready(function(){
$('#countries-list').addClass('hideSection').removeClass('showSection')
});
$('#inputSection').click(function(){
$('#countries-list').addClass('showSection').removeClass('hideSection')
})
</script>
所以当我从列表中点击india JSON时,如果我点击输入部分列表,我应该再次在inputSection中显示印度标志。如果我选择NEPAL,印度标志应该被NEPAL标志取代。
有2个问题。第一,我无法在INNERHTML中编写点击函数来识别点击的国家,第二,如何检索标志部分并将其显示在inputSection中。
任何小提琴都将是非常有帮助和感谢
如果您只需要复制输入部分中的标志部分,那么这就是您所需要的:
$('.listSection').on('click', function() {
$('#inputSection').html( $('.flagSection', this).clone() );
});
但是,您必须将JS中HTML中每次出现的id
转换为class
,如下面的工作演示所示。Id属性值应该是唯一的。
$(function() {
const data = [{
"name": "INDIA ",
"code": "93",
"url": 'https://www.countryflags.io/in/flat/64.png'
}, {
"name": "JAPAN ",
"code": "355",
"url": 'https://www.countryflags.io/jp/flat/64.png'
}];
for (var i = 0; i < data.length; i++) {
var countryName = data[i].name;
var countrtDialCode = data[i].code;
var countryUrl = data[i].url;
var badge = document.createElement('div');
badge.className = 'badge';
badge.innerHTML =
'<div class="listSection">'+
'<div style="display:flex">'+
'<div class="flagSection">'+'<img style="height:10px;width:20px;margin-top:4px;" src='+countryUrl+'>'+'</div>'+' '+
'<div class="nameSection">' + countryName + '</div>' +' '+
'<div class="codeSection">' + countrtDialCode + '</div>'
+'</div>'+
'</div>'
document.getElementById('countries-list').appendChild(badge);
}
$('.listSection').on('click', function() {
console.log( {name: $('.nameSection',this).text(), code: $('.codeSection', this).text()} );
$('#inputSection').html( $('.flagSection', this).clone() );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputSection"> </div>
<div id="countries-list">
</div>
注意
由于文档中没有提到.html( jQueryObject )
,甚至认为它在上面的演示中有效,我将提供一个使用.empty()
和.append()
方法的替代方案:
$('#inputSection').empty().append( $('.flagSection', this).clone() );