使用data-attr识别活动选择

时间:2016-06-11 04:52:27

标签: javascript jquery html5 custom-data-attribute toggleclass

我会尽量保持简单。

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

我有一个 secondary div ,其中selected项目正在显示,而 main div 图标则收到{{} 1}}。

我希望最终用户能够通过点击 active main div 来删除其中的任何一个。< / p>

大多数情况都有效,但我无法找出将它们映射到一起的最佳方法,这样我就可以有两个独立的secondary div来控制相同的结果。

我认为这可能与我动态创建元素的事实有关......这会创建更多元素......这些元素必须改变初始元素。

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

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

HTML:

array

的Javascript / jQuery的:

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

因此,总而言之,我想要一些方法从 {{1}中的项目中删除 // 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); }); } 等效元素中的.active类单击

我尝试通过使用所选项目的main div搜索任何元素来删除课程second div,但我无法让它工作。

例如:

active

我真的想要一些data-color=data-color方法,例如,如果它有$('*[data-color="' + $(this).data('color') + '"]').removeClass('active'); ,则删除该类。

游乐场: https://jsfiddle.net/c75xcLha/

编辑:

两者都被选中,按设计工作:    both selected, both displayed

Clicked Yellow Div。黄色按钮仍处于活动状态:    yellow div clicked on (removed), but the option button remains active

当按下黄色div或按钮时,应从按钮中删除活动类,如下所示:    proper way it should display after clicking yellow div

1 个答案:

答案 0 :(得分:2)

您使用data-* property而不是.data(PROP)分配attribute,因此无法使用data-*访问/选择具有attribute-selector属性的元素,分配{{1}使用attribute代替.attr('data-color')

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

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

  

使用.data(property)更新数据值时,它正在更新由.data()管理的内部对象,因此不会在jQuery [Ref]中更新

data-* attribute
// 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;
}

Updated Fiddle

编辑: 如果您仍想坚持使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <div id="options"></div> <div id="selectedOptions"></div>方法,请使用.data选择目标元素。

.filter