简体   繁体   中英

modifying main view from inside partial view

I have a main view that let's say has the following:

<div id='test'>Some Text</div>

<div id='placeholder'></div>

then using ajax I'm replacing the contents of 'placeholder' with a partial view that looks like this:

<div id='ajaxContent'>
 // new content
</div>

<script>
 $(document).ready(function() {
  console.log($('#test').text());
  $('#test').css('color','red');
 });
</script>

so in my script I'm trying to change the color of the text in div 'test' to red, but I keep getting 'undefined' in the console. How do I access the test div in the main view from the partial view coming into the main view through ajax?

If they're ending up on the same page, shouldn't the html elements be able to see each other?

Your JavaScript fragment is simply removed by jQuery on html(...) call. A similar issue can be found here: jQuery .load() / .ajax() not executing javascript in returned HTML after appended

Thus, you have to insert partial data in this manner (assuming you have your partial respone in result variable):

$(result).find('#ajaxContent').appendTo('#placeholder');
$(result).find('script').appendTo('#placeholder');

Also, as @RolandBertolom said before, you don't need ready() in your partial response in JavaScript.

You actually do not need to use $(document).ready . It's just useless. But it shouldn't break anything. As well as you can access any element on the page from script inserted anywhere in the same document. So problem is somewhere out your question's scope.

Try:

  1. run $('#test').text() from console.
  2. replace $('#test').text() with $('body') or something else in your script.
  3. ...

Be deductive when you debugging! ;-)

you should not be using $(document).ready again because you document will already loaded with main page so again using it wont help. try like this: suppose this is your test.php:

<script>
jQuery(document).ready(function() {

     $.ajax({
            type:'post',
             url:'submit.php',
             success:function(data) {
                 $('#placeholder').append(data);
             }
     });

    });

</script>


        <div id='test'>Some Text</div>

    <div id='placeholder'></div>

//this is your submit.php the content to replace

<?php
echo "<div id='ajaxContent'>

</div>

<script>
$(function(){
    console.log($('#test').text());
    $('#test').css('color','red');
});
</script>";
 ?>

NOTE: what i exactly mean here is use:

 $(function(){
        console.log($('#test').text());
        $('#test').css('color','red');
    }); 

in script.

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