优化重复代码以添加新选项以选择jquery

时间:2017-08-08 04:51:42

标签: javascript jquery

这是我的小提琴:DEMO

我重复了一些代码,用于为规则和事件类别选择添加新选项。如何优化相同以消除重复的代码?

//Adding new category for event
$(document).on('click', '.addevent', function() {

  var found = false; // Track if new value was found in list        
  // Loop through list options
  $("#categoryevent > option").each(function(idx, el) {
    // Compare (case-insensitive) new value against list values
    if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
      alert("Category already exists!")
      found = true; // Set flag if value exists
      $('#new-option-event').val('');
    }
  });
  // If not found
  if ($('#new-option-event').val().trim() != '') {
    if (!found) {
      // Create new option and append to list
      var val = $("#new-option-event").val().trim();
      var opt = '<option>' + val + '</option>';
      $('#categoryevent').append(opt);
      $('#categoryevent').val(val);
      $('#new-option-event').val('');
      $("#categoryevent").click();
    }
  }

});

3 个答案:

答案 0 :(得分:0)

您可以使用一些优化代码https://jsfiddle.net/3tLx884e/2/

&#13;
&#13;
//Adding new category for rule
$(document).on('click', '.addrule', function() {

  var found = false; // Track if new value was found in list		
  // Loop through list options
  var text = $("#new-option-rule").val().trim();
  $("#categoryrule > option").each(function(idx, el) {
    // Compare (case-insensitive) new value against list values
    if (text.toLowerCase() === el.textContent.toLowerCase()) {
      alert("Category already exists!");
      found = true; // Set flag if value exists
    }
    
    if((idx + 1) === $('#categoryrule > option').length){
      if ( !found && (text != '')) {
        // Create new option and append to list
        $('#categoryrule')
        	.append('<option>' + text + '</option>')
          .val(text);
      }
      $('#new-option-rule').val('');
    }
  });
  // If not found
  
});



//Adding new category for event
$(document).on('click', '.addevent', function() {

  var found = false; // Track if new value was found in list		
  // Loop through list options
  $("#categoryevent > option").each(function(idx, el) {
    // Compare (case-insensitive) new value against list values
    if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
      alert("Category already exists!")
      found = true; // Set flag if value exists
      $('#new-option-event').val('');
    }
  });
  // If not found
  if ($('#new-option-event').val().trim() != '') {
    if (!found) {
      // Create new option and append to list
      var val = $("#new-option-event").val().trim();
      var opt = '<option>' + val + '</option>';
      $('#categoryevent').append(opt);
      $('#categoryevent').val(val);
      $('#new-option-event').val('');
      $("#categoryevent").click();
    }
  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label col-sm-2" for="category">Rule Category:</label>
  <div class="col-sm-8">
    <select class="form-control" id="categoryrule" name="category">
      <option>Humidity</option>
      <option>Temperature</option>
      <option>Rule Type3</option>
      <option>Rule Type4</option>
      <option>Rule Miscellaneous</option>
    </select>
  </div>
</div>
<div class="form-group">
  <label class="control-label col-sm-2"></label>
  <div class="col-sm-8">
    <div class="col-sm-8" style="padding-left:0px;">
      <input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
    </div>
    <div class="col-sm-2" style="padding-left:0px;">
      <button class="btn btn-md addrule">Add Category</button>
    </div>
  </div>
</div>

<div class="form-group">
  <label class="control-label col-sm-2" for="category">Event Category:</label>
  <div class="col-sm-8">
    <select class="form-control" id="categoryevent" name="category">
      <option>SMS</option>
      <option>Email</option>
      <option>Invoke API</option>
      <option>Event Type4</option>
      <option>Event Miscellaneous</option>
    </select>
  </div>
</div>
<div class="form-group">
  <label class="control-label col-sm-2"></label>
  <div class="col-sm-8">
    <div class="col-sm-8" style="padding-left:0px;">
      <input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
    </div>
    <div class="col-sm-2" style="padding-left:0px;">
      <button class="btn btn-md addevent">Add Category</button>
    </div>
  </div>
</div>
<div class="actionConfig">
</div>
&#13;
&#13;
&#13;

希望这会对你有所帮助。

答案 1 :(得分:0)

在这里 - 一个常见的功能有很多帮助:

&#13;
&#13;
//Adding new category for rule
$(document).on('click', '.addrule', function() {
  AddElement("categoryrule", "new-option-rule");
});



//Adding new category for event
$(document).on('click', '.addevent', function() {
		AddElement("categoryevent", "new-option-event");
});


function AddElement(selectId, newElementId){
	var found = false; // Track if new value was found in list		
  // Loop through list options
  $( "#" + selectId + " > option").each(function(idx, el) {
    // Compare (case-insensitive) new value against list values
    if ($("#" + newElementId).val().trim().toLowerCase() === el.textContent.toLowerCase()) {
      alert("Category already exists!")
      found = true; // Set flag if value exists
      $('#' + newElementId).val('');
    }
  });
  // If not found
  if ($('#' + newElementId).val().trim() != '') {
    if (!found) {
      // Create new option and append to list
      var val = $("#" + newElementId).val().trim();
      var opt = '<option>' + val + '</option>';
      $('#' + selectId).append(opt);
      $('#' + selectId).val(val);
      $('#' + newElementId).val('');
      $("#" + selectId).click();
    }
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label col-sm-2" for="category">Rule Category:</label>
  <div class="col-sm-8">
    <select class="form-control" id="categoryrule" name="category">
      <option>Humidity</option>
      <option>Temperature</option>
      <option>Rule Type3</option>
      <option>Rule Type4</option>
      <option>Rule Miscellaneous</option>
    </select>
  </div>
</div>
<div class="form-group">
  <label class="control-label col-sm-2"></label>
  <div class="col-sm-8">
    <div class="col-sm-8" style="padding-left:0px;">
      <input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
    </div>
    <div class="col-sm-2" style="padding-left:0px;">
      <button class="btn btn-md addrule">Add Category</button>
    </div>
  </div>
</div>

<div class="form-group">
  <label class="control-label col-sm-2" for="category">Event Category:</label>
  <div class="col-sm-8">
    <select class="form-control" id="categoryevent" name="category">
      <option>SMS</option>
      <option>Email</option>
      <option>Invoke API</option>
      <option>Event Type4</option>
      <option>Event Miscellaneous</option>
    </select>
  </div>
</div>
<div class="form-group">
  <label class="control-label col-sm-2"></label>
  <div class="col-sm-8">
    <div class="col-sm-8" style="padding-left:0px;">
      <input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
    </div>
    <div class="col-sm-2" style="padding-left:0px;">
      <button class="btn btn-md addevent">Add Category</button>
    </div>
  </div>
</div>
<div class="actionConfig">
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这是我对问题的看法,遵循jquery的口号:&#34;少写,多做&#34; ...

我通过处理本地上下文进一步减少了代码。 I. e。我只需要为所有内容定义一个点击事件。点击功能本身会找出要改变的内容。它不需要任何id来完成它的工作:

&#13;
&#13;
//Adding new category for rule and event
$('.form-group').on('click', 'button', addElement);

function addElement(){
  var $grp=$(this).closest('.form-group'),
      ival=$('input:text',$grp).val().trim(),  // new input value
      $sel=$('select',$grp.prev()), // select element
      opts=$.makeArray($('option',$sel).map(function(i,op){
        return op.textContent.toLowerCase(); }));
  if ($.inArray(ival.toLowerCase(),opts)===-1){   // check existing option values
    $sel.append('<option value="'+ival+'" selected>'+ival+'</option>');
  }
  else {alert(ival+' exists already in '+$sel[0].id);}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label col-sm-2" for="category">Rule Category:</label>
  <div class="col-sm-8">
    <select class="form-control" id="categoryrule" name="category">
      <option>Humidity</option>
      <option>Temperature</option>
      <option>Rule Type3</option>
      <option>Rule Type4</option>
      <option>Rule Miscellaneous</option>
    </select>
  </div>
</div>
<div class="form-group">
  <label class="control-label col-sm-2"></label>
  <div class="col-sm-8">
    <div class="col-sm-8" style="padding-left:0px;">
      <input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
    </div>
    <div class="col-sm-2" style="padding-left:0px;">
      <button class="btn btn-md addrule">Add Category</button>
    </div>
  </div>
</div>

<div class="form-group">
  <label class="control-label col-sm-2" for="category">Event Category:</label>
  <div class="col-sm-8">
    <select class="form-control" id="categoryevent" name="category">
      <option>SMS</option>
      <option>Email</option>
      <option>Invoke API</option>
      <option>Event Type4</option>
      <option>Event Miscellaneous</option>
    </select>
  </div>
</div>
<div class="form-group">
  <label class="control-label col-sm-2"></label>
  <div class="col-sm-8">
    <div class="col-sm-8" style="padding-left:0px;">
      <input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
    </div>
    <div class="col-sm-2" style="padding-left:0px;">
      <button class="btn btn-md addevent">Add Category</button>
    </div>
  </div>
</div>
<div class="actionConfig">
</div>
&#13;
&#13;
&#13;