【问题标题】:Applying style to li generated in loop of function将样式应用于函数循环中生成的 li
【发布时间】:2011-07-31 23:49:16
【问题描述】:

@nrabinowitz

我现在想知道如何在单击以将样式应用于上一节中创建的 LI 时获取地图图标。那可能吗?我在下面的代码中尝试过,但不起作用。

function(I) {
    // within the scope of this function,
    // "thismarker" will work as expected
    var listid = I + 1;
    $("<li id="+I+"/>")
        .html('<span class="leadId">' + listid + '</span>' + '<div class="leadDataWrapper"><div class="leadName">' + data[I][3] + ' ' + data[I][4] + '</div><div class="leadDate">' + data[I][2] + '</div></div><div class="leadType"><img src="/images/map-' + data[I][1].toLowerCase() + '.png"></div>')
        .click(function(){
            infowindow.close();
            infowindow.setContent(contentString[I]);
            map.setCenter(markers[I].position);
            infowindow.open(map, markers[I]);

        })
        .appendTo("#leadsList ul");  
    google.maps.event.addListener(marker, "click", function(e){
        infowindow.close();
        infowindow.setContent(contentString[I]);
        infowindow.open(map, markers[I]);
        $("#leadsList li #"+I).css({"background-color":"#666666"});
    });
})(I);

【问题讨论】:

    标签: jquery


    【解决方案1】:

    任何 dom 元素的 id 不能是整数,它应该总是以 alpha 或特殊字符开头。试试这个

    function(I) {
        // within the scope of this function,
        // "thismarker" will work as expected
        var listid = I + 1;
        $("<li id='_"+I+"'/>")
            .html('<span class="leadId">' + listid + '</span>' + '<div class="leadDataWrapper"><div class="leadName">' + data[I][3] + ' ' + data[I][4] + '</div><div class="leadDate">' + data[I][2] + '</div></div><div class="leadType"><img src="/images/map-' + data[I][1].toLowerCase() + '.png"></div>')
            .click(function(){
                infowindow.close();
                infowindow.setContent(contentString[I]);
                map.setCenter(markers[I].position);
                infowindow.open(map, markers[I]);
    
            })
            .appendTo("#leadsList ul");  
        google.maps.event.addListener(marker, "click", function(e){
            infowindow.close();
            infowindow.setContent(contentString[I]);
            infowindow.open(map, markers[I]);
            $("#leadsList li #_"+I).css({"background-color":"#666666"});
        });
    })(I);
    

    【讨论】:

      【解决方案2】:

      li#I 之间有一个空格。这实际上意味着,给我一个 li 的后代并且 ID 为 I 的元素。删除空格以将其更正为 id 为 I 的 li:

      $("#leadsList li#"+I).css({"background-color":"#666666"});
      

      但无论如何,您并不需要大部分选择器。只需引用 id - 除非您有特殊情况。

      $("#"+I).css({"background-color":"#666666"});
      

      【讨论】:

        【解决方案3】:

        您的某些选择器中缺少引号。

        请尝试:$('&lt;li id="' + I + '" /&gt;'),而不是 $("&lt;li id="+I+"/&gt;")

        【讨论】:

          猜你喜欢
          • 2014-12-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多