Iframe Input has uncaught TypeError: Cannot set property 'value' of null

时间:2016-07-11 22:39:52

标签: javascript jquery input

I have an input inside an iframe that I would like to put in a preloaded value after the page has loaded. I've put in this code so far:

<script>
    jQuery('iframe').load(function(){
             jQuery('iframe').contents().find('input#ysi_subject').bind('change',function(e)     {
            var title_name = "DO I LOOK LIKE I'M WORKING?";
            jQuery('input#ysi_subject').val(title_name);
         });
    });
</script>

but when I look at the console log, I get this error: Uncaught TypeError: Cannot set property 'value' of null

Can anyone help explain why it's not catching the input?

2 个答案:

答案 0 :(得分:1)

This is because you are trying to access the DOM prior to the DOM elements actually being loaded, so any references to the DOM in this case will output null. Place the code in a $(document).ready() handler in order for this to work:

... <!-- jQuery reference -->
<script>
    $(document).ready(function() {
        // your code that you are trying to run
    });
</script>

* Note that I simplified it down to show what I am really talking about.

答案 1 :(得分:0)

更改事件从iframe内部返回到父窗口。 $(“input#si_subject”)在父窗口中不存在。

    jQuery('iframe').load(function(){
       jQuery('iframe').contents().find('input#ysi_subject').bind('change',function(e)      {
         var title_name = "DO I LOOK LIKE I'M WORKING?";
         // this would work            
         jQuery('iframe').contents().find('input#ysi_subject').val(title_name);
         // this is better
         $(this).val(title_name);
       });
    });