javascript - 使用 data-attr 来识别事件选择

标签 javascript jquery html custom-data-attribute toggleclass

我会尽量保持简单。

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

我有一个 secondary div 其中selected项目正在出现,而 main div 图标接收类别 active .

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

其中大部分都有效,但我无法找出将它们映射在一起的最佳方法,以便我有 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);
  });
}

所以,总而言之,我想要一些方法来删除 .active来自 的类 main div 相当于元素,当项目来自 second div被点击。

我尝试删除类 active通过搜索带有 data-color=data-color 的任何元素所选项目的,但我无法使其工作。

例如:

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

我真的很想要一些data解决此问题的方法,例如删除事件类(如果它有 data-color="yellow")例如。

Playground : https://jsfiddle.net/c75xcLha/

编辑:

两者均已选择,按设计工作: both selected, both displayed

点击黄色分区。黄色按钮仍然有效: yellow div clicked on (removed), but the option button remains active

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

最佳答案

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


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选择目标元素。

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

关于javascript - 使用 data-attr 来识别事件选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37760043/

相关文章:

javascript - 具有半透明背景的堆叠模态显示具有更亮 Angular 落的异常背景

javascript - ie9 - FormData 未定义 - javascript

php - 使用jquery模态形式将数据插入MYSQL

jquery - 使用 .append() 跳过第一个元素

javascript - highcharts 工具提示不移动下一点

javascript - 使用 jquery 重新加载 div 元素

javascript - 单击按钮时显示进度 Dynamics CRM 365

java - Firefox 4 中的小程序问题

javascript - 当 Backbone View 仍在组装 DOM 元素时,如何在 DOM 元素上设置事件触发器?

javascript - 按钮标签 jQuery DataTable