开发者

Jquery multiple elements

i am generating multiple span element all of the same id

<span id='myLink'>some text</span>

and using jquery i wa开发者_高级运维nt to open a div overlay near it using the offset of the span element but when i call a function it only works for the first span element

$('#myLink').click(function() {
            var divOverlay= jQuery('<div id="divOverlay">text on overlay </div>');
            var off=$(this).offset();
            divOverlay.css(
            {
                left:(off.left)+'px',
                top:(off.top-200)+'px'
            });
            divOverlay.appendTo(document.body)

        });

thanks


all of the same id

is causing the problems, Id's must be unique.

Use a class instead

<span id='myLink1' class='myLinkClass'>some text</span>
<span id='myLink2' class='myLinkClass'>some text</span>
<span id='myLink3' class='myLinkClass'>some text</span>


IDs in the DOM are meant to refer to only one element. Give all those spans a class like:

<span class="myClass">some text</span>

and then target them by class:

$('span.myClass').click(function() {
            var divOverlay= jQuery('<div class="divOverlay">text on overlay </div>');
            var off=$(this).offset();
            divOverlay.css(
            {
                left:(off.left)+'px',
                top:(off.top-200)+'px'
            });
            divOverlay.appendTo(document.body)

        });


You can't use the same id on several elements in the same document, it should be unique, use class instead

<span class='myLink'>some text</span>

and

$('.myLink').click(function() {
        var divOverlay= jQuery('<div id="divOverlay">text on overlay </div>');
        var off=$(this).offset();
        divOverlay.css(
        {
            left:(off.left)+'px',
            top:(off.top-200)+'px'
        });
        divOverlay.appendTo(document.body)

    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜