使用 data-attr 识别活动选择

Using data-attr to identify an active selection

我会尽量保持简单。

我有一个通过 AJAX 拉取的 JSON 对象。我正在 main div 中动态显示来自数据的图标列表,可以打开或关闭这些图标。

我有一个 secondary div,其中 selected 项出现,而 main div 图标收到 active 的 class。

我希望最终用户能够通过在 main div[=15= 上单击它们来删除它们中的任何一个].

其中大部分工作正常,但我无法找到将它们映射在一起的最佳方法,因此我有 2 个单独的 click events 可以控制相同的结果。

我认为这可能与以下事实有关:我正在动态创建元素...创建更多元素...必须更改初始元素。

到目前为止,我的结构是将当前选择映射到 array 中。这使我能够控制保留所选所有内容的基于代码的列表(数据比我将提供的示例中的数据多得多)。

所以,到目前为止我是这样的:

HTML:

<div id="options"></div>
<div id="selectedOptions"></div>

Javascript/jQuery:

// Simple simulated AJAX data
var ourData = {
  "color1": "yellow",
  "color2": "blue"
};
var $options = $('#options');
var $selectedOptions = $('#selectedOptions');
// Array to keep track of which objects are selected
var selectedOptions = [];

// Makes the initial option dynamic list
makeOptions(ourData, $options);

// If an option from the main div is clicked, handle class changing
$('button').on('click', function(){
    pickOption($(this));
});

/* This function is the problem. The option gets removed from the array, and from the secondary div, but the class of active still occurs on the main div. */
$selectedOptions.on('click', '.optionActive', function(){
  var option = $(this).data('color');
  var optionPosition = jQuery.inArray(option, selectedOptions);
  selectedOptions.splice(optionPosition, 1);
  displayOptions(selectedOptions, $selectedOptions);
});

// Creates initial icons (buttons in this case) to the DOM and applies a data-attribute for the color
function makeOptions(options, $container){
    var $results = $('<div id="results">');
  $.each(options, function(key, value){
    var $optionButton = $('<button>' + key + ':' + value + '</button>');
    $optionButton.data('color', value);
    $results.append($optionButton);
  });
  $container.append($results);
}

/* Handler for selecting an option from the Main Div. Handling the class active.
I am not using a simple classToggle because there are many situations where a click is not allowed */
function pickOption($option){
  var selectedOption = $option.data('color');
  // If the option returns true, or that it doesn't exist yet
  if(modifyOptions(selectedOption, selectedOptions)){
    $option.addClass('active');
  } else {
    $option.removeClass('active');
  }
  // Recreate our current selected options
  displayOptions(selectedOptions, $selectedOptions);
}

/* Searches array to see if the option exists. Returns true or false and either pushes or splices the option from the array */
function modifyOptions(option){
  var optionPosition = jQuery.inArray(option, selectedOptions);
  if(optionPosition == -1){
    selectedOptions.push(option);
    return true;
  } else {
    selectedOptions.splice(optionPosition, 1);
    return false;
  }
}

/* Displays all currently selected options that exist in our array */
function displayOptions(selectedOptions, $container){
  $container.empty();
  $.each(selectedOptions, function(option, value){
    var $optionTile = $('<div class="optionActive">');
    $optionTile.data('color', value)
                          .text(option + ":" + value)
                .css('background', value);
    $container.append($optionTile);
  });
}

所以,总而言之,我想要一些方法从 main div 等效元素中删除 .active class从 second div 被点击。

我尝试通过搜索任何包含所选项目 data-color=data-color 的元素来删除 class active,但我无法让它工作。

例如:

$('*[data-color="' + $(this).data('color') + '"]').removeClass('active');

我真的很想要一些 data 方法来解决这个问题,例如删除 class 活动,如果它有 data-color="yellow" 例如。

操场: https://jsfiddle.net/c75xcLha/

编辑:

两者均已选中,按设计工作:

单击黄色 Div。黄色按钮仍然有效:

应该在按下黄色 div 或按钮时从按钮中删除活动的 class,如下所示:

您正在分配 data-* property 使用 .data(PROP),而不是 attribute 因此具有 data-* 属性 的元素不能使用 [=] accessed/selected 18=],使用 .attr('data-color') 代替 .data(property)

分配 attribute

Attribute Equals Selector [name=”value”],选择具有指定属性且值正好等于某个值的元素。

.data( key, value ),存储与匹配元素关联的任意数据。

When you use .data() to update a data value, it is updating internal object managed by jQuery, so it will not be updated in the data-* attribute[Ref]


// Simple simulated AJAX data
var ourData = {
  "color1": "yellow",
  "color2": "blue"
};
var $options = $('#options');
var $selectedOptions = $('#selectedOptions');
// Array to keep track of which objects are selected
var selectedOptions = [];

// Makes the initial option dynamic list
makeOptions(ourData, $options);

// If an option from the main div is clicked, handle class changing
$('button').on('click', function() {
  pickOption($(this));
});

/* This function is the problem. The option gets removed from the array, and from the secondary div, but the class of active still occurs on the main div. */
$selectedOptions.on('click', '.optionActive', function() {
  var option = $(this).data('color');
  var optionPosition = jQuery.inArray(option, selectedOptions);
  selectedOptions.splice(optionPosition, 1);
  $('[data-color="' + $(this).data('color') + '"]').removeClass('active');
  displayOptions(selectedOptions, $selectedOptions);
});

// Creates initial icons (buttons in this case) to the DOM and applies a data-attribute for the color
function makeOptions(options, $container) {
  var $results = $('<div id="results">');
  $.each(options, function(key, value) {
    var $optionButton = $('<button>' + key + ':' + value + '</button>');
    $optionButton.attr('data-color', value);
    //___________^^^^^^^^^^^^^^^^^^Little trick here!
    $results.append($optionButton);
  });
  $container.append($results);
}

/* Handler for selecting an option from the Main Div. Handling the class active.
I am not using a simple classToggle because there are many situations where a click is not allowed */
function pickOption($option) {
  var selectedOption = $option.data('color');
  // If the option returns true, or that it doesn't exist yet
  if (modifyOptions(selectedOption, selectedOptions)) {
    $option.addClass('active');
  } else {
    $option.removeClass('active');
  }

  // Recreate our current selected options
  displayOptions(selectedOptions, $selectedOptions);
}

/* Searches array to see if the option exists. Returns true or false and either pushes or splices the option from the array */
function modifyOptions(option) {
  var optionPosition = jQuery.inArray(option, selectedOptions);
  if (optionPosition == -1) {
    selectedOptions.push(option);
    return true;
  } else {
    selectedOptions.splice(optionPosition, 1);
    return false;
  }
}

/* Displays all currently selected options that exist in our array */
function displayOptions(selectedOptions, $container) {
  $container.empty();
  $.each(selectedOptions, function(option, value) {
    var $optionTile = $('<div class="optionActive">');
    $optionTile.data('color', value)
      .text(option + ":" + value)
      .css('background', value);
    $container.append($optionTile);
  });
}
.active {
  background: #CCF;
}
.optionActive {
  min-width: 100px;
  min-height: 100px;
  display: inline-block;
  margin: 1em;
  background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="options"></div>
<div id="selectedOptions"></div>

Updated Fiddle

编辑: 如果您仍想坚持使用 .data 方法,请使用 .filter 到 select 目标元素。

$('button').filter(function(){
  return $(this).data('color')=='yellow';
}).removeClass('active');