开发者

If Clause Issue with img Generation

开发者 https://www.devze.com 2023-02-25 11:00 出处:网络
Script is as follows; $(\"#Results a\").live(\'dblclick\', function(event){ var src = $(this).attr(\"href\");

Script is as follows;

$("#Results a").live('dblclick', function(event){
    var src = $(this).attr("href");
    if (event.type === 'dblclick') {
        if ($(this).hasClass(".A")) {
            $('<img />', {'src': src,'class': 'Box'}).wrap('<div class="Packet" />').parent().insertAfter($('.Spot_A').parent());
        } else if ($(this).hasClass(".B")) {
            $('<img />', {'src': src,'class': 'Box'}).wrap('<div class="Packet" />').parent().insertAfter($('.Spot_B').parent());
        }
    }
});

I double click a link tag to create an img element that uses the href of the link for the src of the image, and places this img somewhere specific, based on the class the link element had. The img element creation part works perfectly. However, i'm now trying to 'sort' the various imgs based on what class the link tag had. This is where i'm having trouble. To me, it seems dead obvious how it should go, but it fails to work.

I figured, it should simply be: When i double click a link, if this (the link) has class __, create an img HERE. If a diff class, then create an img HERE. Note that the links aren't being deleted at any point.

The .parent/insertafter/parent part is necessary because its a part of how the placement within the hierarchy is determined. Spot_A/B is the starting po开发者_运维问答int, and this is the key for the sorting.


.hasClass() takes the name of a class, not a class selector. Remove the periods.

if ($(this).hasClass("A")) {
    // stuff
} else if ($(this).hasClass("B")) {
    // other stuff
}

Giving this the full cleanup treatment:

$('#Results a').live('dblclick', function(event) {
    var $this = $(this),
        src = $this.attr('href'),
        target = $this.hasClass('A') ? '.Spot_A'
               : $this.hasClass('B') ? '.Spot_B'
               : null;

    if (target) {
        $(target).parent().after($('<div class="Packet"></div>').append($('<img />', {'src': src, 'class': 'Box'})));
    }
});
  • Don't repeatedly wrap this, store $(this) in a local variable
  • There is no need to check for event.type === 'dblclick'
  • Be consistent with single vs double quotes
  • Stay DRY
  • This is more a matter of personal preference, but a simple if-else case can be written more tersely with two sets of ternary operators
  • As per the jQuery docs, tags that can contain other elements should be paired with a closing tag (when using $() to create new elements)
  • Clean up the element creation calls
0

精彩评论

暂无评论...
验证码 换一张
取 消