很抱歉我的菜鸟问题,但我有一个适用于大型形式的特定领域的函数。我知道我可以对每个可能的字段进行硬编码,但我想让我的代码保持干燥。我可以做什么来将这种独特的功能添加到表单中的每个字段中。 (它们都共享一个公共(public)类,但我无法让它工作。)
<强> My Fiddle
这是我的 HTML
<form id="form">
<div class="searchContainer">
<select name="mySelect" id="nameEx" class="allS">
<option value="1" selected="selected">AND</option>
<option value="2">EXCLUDE</option>
<option value="3">OR</option>
</select>
<input class="textArea" id="name" name="name" placeholder="Name" style="margin: 0 auto;" type="text">
</div>
<br>
<div class="searchContainer">
<select name="mySelect" id="numberEx" class="allS">
<option value="1" selected="selected">AND</option>
<option value="2">EXCLUDE</option>
<option value="3">OR</option>
</select>
<input class="textArea" id="number" name="number" placeholder="Phone Number" style="margin: 0 auto;" type="text">
</div>
<br>
<div class="searchContainer">
<select name="mySelect" id="cityEx" class="allS">
<option value="1" selected="selected">AND</option>
<option value="2">EXCLUDE</option>
<option value="3">OR</option>
</select>
<input class="textArea" id="city" name="city" placeholder="City" style="margin: 0 auto;" type="text">
</div>
</form>
<div id="name_here" class="summaryParams"></div>
这是我的 JS
$(".searchContainer").change(function () {
var str = '';
if ($('#name').val().length > 0)
var str = $('#nameEx>option:selected').text() + ' Name: ' + $('#name').val();
$("#name_here").html(str);
});
$('#name_here').on('click', function() {document.getElementById("name").value = '';
$("#name_here").html("");
});
PS 这些字段需要返回不同且单独的结果。 谢谢
最佳答案
如果我正确理解你的问题,你可以像这样使用 each()
。
$(".searchContainer").each(function(){
$(this).change(function(){
// code to run on change on each .searchCOntainer
});
});
我认为这很接近你想要的。 Fiddle
$(".searchContainer").each(function(){
$(this).change(function () {
var input = $(this).find('.textArea');
var str1 = $('#name_here').text();
var str2 = '';
if (input.val().length > 0) {
var str2 = $(this).find('option:selected').text() + ' ' + input.attr('placeholder') + ': ' + input.val();
}
$("#name_here").html(str1 + ' ' + str2);
});
});
$('#name_here').on('click', function() {
document.getElementById("name").value = '';
$("#name_here").html("");
});
关于javascript - 如何使 js 函数通用以在我的表单上的任何地方工作? (干燥),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30791554/