根据文本区域值jQuery附加行和标签(减少重复性)



我已经编写了一些代码,但问题是我需要对每一行反复使用jQuery append。我不知道如何缩短它,以便当我在文本区域输入值时,它会根据需要自动添加或删除行(因为如果我有100或200行要添加,这个代码会很困难(。

$(document).ready(function() {
$('.position').bind("change keyup input", function() {
var pos = $('.position').val().split(',');
var hght = $('.height').val().split(',');
var lbl = $('.label').val().split(',');
$('.peak').remove();
$('.matchi').append("<div class='peak' style='left:" + pos[0] + "%;height:" + hght[0] + "%'>" + lbl[0] + "</div>").append("<div class='peak' style='left:" + pos[1] + "%;height:" + hght[1] + "%'>" + lbl[1] + "</div>").append("<div class='peak' style='left:" + pos[2] + "%;height:" + hght[2] + "%'>" + lbl[2] + "</div>").append("<div class='peak' style='left:" + pos[3] + "%;height:" + hght[3] + "%'>" + lbl[3] + "</div>")
});
});
.peak {
background: red;
height: 100%;
width: 0.5%;
position: absolute;
bottom: 0
}
<textarea class='position'>
20, 45, 60, 85, 95
</textarea>
<textarea class='height'>
100, 50, 90, 30, 25
</textarea>
<textarea class='label'>
peak-132, peak-432, peak-847, peak-743, peak-536
</textarea>
<div class='matchi' style='position:relative;background:#eee;padding-top:18%' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

您可以基于.position值对编译后的html进行map()

$(document).ready(function() {
$('.position, .height, .label').on("input", function() {
var pos = $('.position').val().split(',');
var hght = $('.height').val().split(',');
var lbl = $('.label').val().split(',');
$('.peak').remove();
let html = pos.map((p, i) => `<div class='peak' style='left:${pos[i]}%;height:${hght[i]}%'>${lbl[i]?lbl[i]:''}</div>`);
$('.matchi').html(html)
});
});
.peak {
background: red;
height: 100%;
width: 0.5%;
position: absolute;
bottom: 0
}
<textarea class='position'>
20, 45, 60, 85, 95
</textarea>
<textarea class='height'>
100, 50, 90, 30, 25
</textarea>
<textarea class='label'>
peak-132, peak-432, peak-847, peak-743, peak-536
</textarea>
<div class='matchi' style='position:relative;background:#eee;padding-top:18%' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

最新更新