在尝试访问弹出元素时,使用magnificPopup打开的弹出窗口中的getElementById失败

时间:2014-11-24 13:44:53

标签: javascript jquery html magnific-popup

使用getElementById失败,导致它尝试在"中找到id为#34;的元素。在父亲HTML中。如何获取输入元素的内容" id"从弹出窗口?

<html>
<head>
    <link media="all" type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/magnific-popup.css">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/0.9.9/jquery.magnific-popup.min.js"></script>
</head>
<body>
    <button id="someid">Open popup</button>

<script>
    $('#someid').magnificPopup({
                                          items: {
                                              src:  
                                                    '<div class="white-popup"><br>\
                                                    <input id="in" type="text" placeholder="content">\
                                                    <a href=document.getElementById('in')>Click</a>',

                                              type: 'inline'
                                          }
                           });  
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您可以使用事件委派,例如

1

$('#someid').magnificPopup({
  items: {
    src: [
        '<div class="white-popup"><br>',
        '<input id="in" type="text" placeholder="content">',
        '<a href="#">Click</a></div>'
    ].join(),

    type: 'inline'
  }
});

$('body').on('click', '.white-popup > a', function () {
  alert($(this).siblings('#in').val());
})

演示:http://jsbin.com/votam/1/

2或

$('#someid').magnificPopup({
  items: {
    src: [
        '<div class="white-popup"><br>',
        '<input id="in" type="text" placeholder="content">',
        '<a href="javascript:alert(document.getElementById(\'in\').value);">Click</a></div>'
    ].join(),

    type: 'inline'
  }
});

DEMO:http://jsbin.com/votam/2/

3

$('#someid').magnificPopup({
  items: {
    src: [
        '<div class="white-popup"><br>',
        '<input id="in" type="text" placeholder="content">',
        '<a href="url?arg1=\'arg1\'&arg2=" onclick="this.href = this.href + document.getElementById(\'in\').value ">Click</a></div>'
    ].join(),

    type: 'inline'
  }
});

演示:http://jsbin.com/votam/3/edit