开发者

Jquery, add buttons under elements, and remember which element the button belongs to

Please check out my code here

http://jsfiddle.net/bYDPr/20/

So I have some HTML textarea elements

<textarea id="area11ba" class="showEditor">1</textarea><br/>
<textarea id="area22ab" class="showEditor">2</textarea><br/>
<textarea id="area33cd" class="showEditor">3</textarea><br/>
<textarea id="area4fg">4</textarea><br/>
<textarea id="area55ed" cla开发者_C百科ss="showEditor">5</textarea><br/>

And I wanna add an "Editor" button under each textarea that has "showEditor" class, then when people click on the Editor button, it should alert the content of that textarea.

Here is my attempt

$("textarea[class*='showEditor']").each(function(index) {

    textareaid = $(this).attr('id');
    buttonId = "editorButton" + index;
    editorButton = '<div class="editorButton"><a id="' + buttonId + '">Editor</a></div>';
    $(editorButton).insertAfter(this);

    that = this;

    $('#' + buttonId).click(function() {
        content = $('#'+ textareaid ).val();
        alert(content);
    });


});

But unfortunately the alerted value is always 5, which is the last defined element.

How can this be done properly?

Thanks


Not sure if you mean to skip "showEditor" class for area 4, but if not, here's the result: http://jsfiddle.net/bYDPr/8/

Basically, change

content = $(that).val();

to

content = $('#area' + (index+1)).val();

EDIT: Change "that = this;" to "var that = this;"

$("textarea[class*='showEditor']").each(function(index) {

        buttonId = "editorButton" + index;
        editorButton = '<div class="editorButton"><a id="' + buttonId + '">Editor</a></div>';
        $(editorButton).insertAfter(this);

        var that = this;

        $('#' + buttonId).click(function() {
            content = $(that).val();
            alert(content);
        });     
});


The problem here is the scope of the evaluation of 'this'.

Try this solution: http://jsfiddle.net/richfreedman/bfVnm/1/

$("textarea[class*='showEditor']").each(function(index) {

    buttonId = "editorButton" + index;
    editorButton = '<div class="editorButton"><a id="' + buttonId + '">Editor</a></div>';
    $(editorButton).data("editor", this).insertAfter(this).click(function(event) {
        textarea = $(this).data("editor")
        alert($(textarea).val())
    });
});


$(function(){
    $('.editorButton').live('click', some_function);
});

function some_function(){
    content = $(this).prev().val();
    alert(content);
}


$('.showEditor').each(function(index){
    buttonId = "editorButton" + index;
    editorButton = '<div class="editorButton"><a id="' + buttonId + '">Editor</a></div>';
    $(this).insertAfter(editorButton);
});



Edited: in response to your changes.


You missed the var before declaring the variables !

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜