我创建了一个小应用程序,可帮助创建长而重复的产品说明。有几个类别,每个类别下都有许多预先制作的段落;点击一个段落会自动将其添加到正在创建的完整描述中(这就是它的外观和工作方式:https://gfycat.com/AnguishedBestChinesecrocodilelizard)。
每个类别都有自己的变量。这就是HTML的样子:
<!-- Setting variables -->
<div class="col-sm-4">
<label for="resolution">Resolution:</label> <input type="text" id="resolution" placeholder="1234 x 4321">
<input type="button" id="setresolution" value="SET"></div>
<div class="col-sm-4">
<label for="quality">Quality:</label> <input type="text" id="quality" placeholder="ie. FullHD, HD, 4K, UHD">
<input type="button" id="setquality" value="SET"></div>
<div class="col-sm-4">
<label for="screensize">Screen size:</label> <input type="text" id="screensize" placeholder='w/ unit, ie. 4 inches or 4"'>
<input type="button" id="setscreensize" value="SET"></div>
(...)
<!-- paragraphs with placeholders that will be replaced by values set above -->
<div class="box"><div class="kol_<span class="kolx">100</span>" style="text-align: center; "><h3><b>See more</b></h3> <span><b> A big, <span class="inchx">[5,5"]</span> screen? Sure, why not. But only if it's <span class="qualityx">[QUALITY]</span> screen – just like here! An amazing <span class="qualityx">[QUALITY]</span> screen allows you to fully enjoy all those beautiful photos.</b></span> </div></div>
<div class="box"><div class="kol_<span class="kolx">100</span>" style="text-align: center; "><h3><b>Crystal clear</b></h3> <span><b>This device has an amazing <span class="resolutionx">[RES]</span> screen, so you can see everything perfectly.</b></span> </div></div>
JS:
$(function() {
$("#setresolution").click(function() {
$(".resolutionx").empty();
$(".resolutionx").append($('#resolution').val());
toastr.success('Done');
});
});
$(function() {
$("#setquality").click(function() {
$(".qualityx").empty();
$(".qualityx").append($('#quality').val());
toastr.success('Done');
});
});
$(function() {
$("#setscreensize").click(function() {
$(".inchx").empty();
$(".inchx").append($('#screensize').val());
toastr.success('Done');
});
});
它有效,但它非常不优雅,因为JS片段基本上一遍又一遍地重复,只有目标在变化。我试图创建一个更大的通用功能来处理所有情况,但我不确定如何,因为我迄今为止的所有尝试都失败了。
有人可以伸出援助之手吗? :)
答案 0 :(得分:0)
这是重构的简单应用。
每个区块似乎只有三个不同的东西:
所以那些可以是函数的参数:
function registerField(button, clazz, field) {
$(button).on('click', function() {
$(clazz).empty().append($(field).val());
toastr.success('Done');
});
}
样本用法:
$(function() {
registerField('#setquality', '.qualityx', '#quality');
...
});