簡體   English   中英

jQuery觸發第n個元素onload的委托事件

[英]jquery Trigger delegate event for nth element onload

在我的頁面中,我有10張圖像,所有圖像都具有相同的類“ select-option”

我的HTML是

<div class="select-option swatch-wrapper selected" data-name="A Very Scary Monster" data-value="a-very-scary-monster">
<a href="#" style="width:120px;height:120px;" title="" class="swatch-anchor">
<img src="image ur1" alt="" class="" width="120" height="120"></a></div>

同樣,我有10張圖片。

  function init_swatches() {

      $('.select-option').delegate('a', 'click', function(event) {
          ///////////// Some code here
        var $the_option = $(this).closest('div.select-option');

      });
}

我想預選第3張圖片。 選擇的圖像具有“選擇”類,其他圖像則沒有。 如何為加載的第3個或第4個元素觸發此操作。 如何為第n個元素手動觸發此委托事件。

在這里我想觸發這個點擊事件

你可以使用jQuery的觸發方法

function init_swatches() {

  $('.select-option').delegate('a', 'click', function(event) {
      ///////////// Some code here
    var $the_option = $(this).closest('div.select-option');

  });
  $('.select-option a').eq(2).trigger("click");
}

錨定標記上的首次綁定點擊事件

$('.select-option').delegate('a', 'click', function(event) {
          ///////////// Some code here
        var $the_option = $(this).closest('div.select-option');

  });

然后手動觸發第三個元素的點擊事件,如下所示

$('.select-option a').eq(2).click()

要么

  $('.select-option a').eq(2).trigger("click")

我不確定您是否要觸發click事件,而是使用click事件來設置選定的類。 像這樣的東西可能更合適:

$(document).ready(function() {
    $(document).delegate(".select-option", "click", function(e) {
        if ($(this).hasClass("selected") == false) {
            $(".select-option.selected").removeClass("selected");
            $(this).addClass("selected");
        }
    });
    selectNthImage(3);
});

function selectNthImage(n) {
    $(".select-option.selected").removeClass("selected");
    $(".select-option:nth-child(" + n + ")").addClass("selected");
};

在這里查看jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM