开发者问题收集

JavaScript 事件监听器未添加到按钮

2013-12-15
336

我的代码中有一个 <button> ,其 id 为 button_edit_post,而我的 java 脚本不会向其添加事件侦听器。

document.onload = function(){
    document.getElementById('button_edit_post').addEventListener('click', function(){
        alert("event listener added");
        var data = document.getElementById('edit_post').innerHTML;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert("data added");
            };
        };
        var php = data + "q=" + post_id;
        console.log(php);
        xhr.open("POST", "edit_post.php?p="+php, true);
        xhr.send();
    }, false);
};

HTML:

<article>Edit blog post
    <section><div id="admin_subtitle">Select the post you want to edit then modify the text</div>
            <select name="edit" id='edit' onchange='editPost(value)'>
                    <option>Please select a post..</option>
                    <?php
                    $result = mysql_query("SELECT BlogPostID, BlogPostTitle FROM blogpost ORDER BY BlogPostID DESC");
                    while ($row = mysql_fetch_array($result)){
                        $blogvar  = array($row ['BlogPostID'], $row ['BlogPostTitle']);
                    ?>
                    <option value="<?php echo $blogvar[0]; ?>" id='edit_option'><?php echo $blogvar[1]; ?></option>
                    <?php
                    };
                    ?>
                </select>
                <div id='gif_loader'></div>
                <div id='text_edit_area' style='display: none;'>
                    <textarea id='edit_post' rows='30' cols='200'></textarea>
                    <button id='button_edit_post'>Edit Post</button>
                </div>

任何帮助都很好,

谢谢 :)

1个回答

应为 window.onload = function ,或者实际上只是 onload = function ,因为 window 是隐式的。

StackSlave
2013-12-15