简体   繁体   中英

Replacing different text, onClick, to SAME div

I'm pretty new to javascript and have been at this at awhile, but still can't figure it out, so any advice as how to continue this, would be much appreciated. I've tried to place it in a jsFiddle, but it does not work, even when part of the code is working on my computer. I've got the first part (#preheat and #pans) to do what I want.

javascript:

<script>    
    $(function () {   
        $('#preheat').on('click', function () {
            $("<p>Preheat oven to 350°F. Prepare two 9-inch pans by spraying with baking spray.</p>").appendTo('#content');

            $("#steps").replaceWith('<span id="steps1">Allow to <span id="verb_1">cool</span> for about 10 minutes, remove from <span id="noun_1">pans </span>and cool completey.</span>');   
        });


//this part is not working
        $('#cool').on('click', function () {
            $("<p>Allow to cool for about 10 minutes, remove from pans and cool completely.</p>").appendTo('#content');

            $("#steps1").replaceWith('<span id="verb_2">Bake</span><span id="noun_2">chocolate cake</span> for 30-35 minutes, until a toothpick or cake tester inserted in the center comes out clean.'); 
        }); 

        $('#pans').on('click', function () {
            $("<p>Preheat oven to 350°F. Prepare two 9-inch pans by spraying with baking spray.</p>").appendTo('#content');

            $("#steps").replaceWith('<span id="verb1">Distribute</span> cake batter evenly between the <span id="noun1">two cake pans.</span>');
        });    

    });
</script>

html:

    <div id="steps">
            <span id="preheat">Preheat</span>
            <span>oven to 350°F. Prepare</span>
            <span id="pans">two 9-inch pans</span>
            <span>by spraying with baking spray.</span>
        </div>



    <div id="content">
        <p></p>
   </div>

css:

 #content{
    float:right;
}
$('#cool').on('click', function () {

is not working becauase there is not element with id cool .

Also, if you want to delegate a click event for element having id cool do

$(document).on('click',''#cool', function () { // you can use any valid selector for a parent element of #cool instead of document

something like this JSFiddle is probably what you need.

Updated JSFiddle

side note: at the end of your code, you're trying to replace #steps which do not exists any more since you replaced it with something else earlier. You might want to use html() function instead of replaceWith() as in this JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM