Replace Div Content onclick

前端 未结 6 997
名媛妹妹
名媛妹妹 2020-12-06 07:48

I know nothing about jQuery but want to achieve something really important.

I want to have a button/link that will replace the div content and if I press that button

6条回答
  •  北海茫月
    2020-12-06 08:08

    EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.


    Here is an example of how it could work:

    Working jsFiddle Demo

    HTML:

    Once upon a midnight dreary
    While I pondered weak and weary
    Over many a quaint and curious
    Volume of forgotten lore.
    Type new text here:

    javascript/jQuery:

    //Declare persistent vars outside function
    var savText, newText, myState = 0;
    
    $('#mybutt').click(function(){
        if (myState==0){
            savText = $('#someDiv').html(); //save poem data from DIV
            newText = $('#replacementtext').val(); //save data from input field
            $('#replacementtext').val(''); //clear input field
            $('#someDiv').html( newText ); //replace poem with insert field data
            myState = 1; //remember swap has been done once
        } else {
            $('#someDiv').html(savText);
            $('#replacementtext').val(newText); //replace contents
            myState = 0;
        }
    });
    

提交回复
热议问题