Javascript函数锚点onclick语法

时间:2012-05-06 15:37:34

标签: html syntax hyperlink onclick

我有以下脚本用于评论系统很好地工作,直到我将参数放入函数调用。现在,它不是执行函数,而是重新加载页面并将我提升到顶部。 (之前,我没有撞到并且很好地插入盒子。)任何人都可以在下面看到错误。注意,我认为#不是从链接调用函数的首选方法,但对于这个简单的函数调用,其他方式似乎相当复杂。非常感谢。

注意此页面是一个文本字符串,即“comments.php”,而id和topicid是整数。

<script>
function showReplyBox(id,topicid,thispage) {
    var replybox = '<form action = "newcomment.php" method = "post"><input type="hidden" name="comid" value="';
replybox = replybox+ id + '">';
replybox = replybox + '<input type="hidden" name="topicid" value="';
replybox = replybox + topicid + '">';
replybox = replybox + '<input type="hidden" name="thispage" value="';
replybox = replybox + thispage + '">';
replybox = replybox + '<textarea autofocus placeholder="Reply to comment" id="replyarea" rows=1 cols=72></textarea><br><button>Reply</button></form>';
    var empty = ""; 

document.getElementById('replybox').innerHTML = replybox;
}
</script>
<body>
//link to call function
<a href="#" onclick="showReplyBox(44,142,'comments.php');return false">Reply</a

//box inserted here
<div id="replybox"></div>
</body>

3 个答案:

答案 0 :(得分:4)

使用#

替换锚标记中的javascript:void(0)
<a href="javascript:void(0);" onclick="showReplyBox(44,142,'comments.php');return false">Reply</a>

答案 1 :(得分:4)

让函数在末尾返回false以防止浏览器跟随锚点的默认行为。

这是一个有效的小提琴:http://jsfiddle.net/VhYd8/

答案 2 :(得分:0)

<body>
//link to call function
<a href="#" id="my_a" t_id=44 t_tid=142 t_php="comments.php">Reply</a>
<script>
    function showReplyBox(event) {
        event.preventDefault();
        var tar_a = e.target;
        var id = tar_a .getAttribute("t_id");
        var topicid = tar_a .getAttribute("t_tid");
        var thispage = tar_a .getAttribute("t_php");

        var replybox = '<form action = "newcomment.php" method = "post"><input type="hidden" name="comid" value="';
        replybox = replybox+ id + '">';
        replybox = replybox + '<input type="hidden" name="topicid" value="';
        replybox = replybox + topicid + '">';
        replybox = replybox + '<input type="hidden" name="thispage" value="';
        replybox = replybox + thispage + '">';
        replybox = replybox + '<textarea autofocus placeholder="Reply to comment" id="replyarea" rows=1 cols=72></textarea><br><button>Reply</button></form>';
        var empty = ""; 

        document.getElementById('replybox').innerHTML = replybox;
    }
    doucument.getElementById("my_a").addEventListener('click',showReplyBox,false);
</script>
//box inserted here
<div id="replyarea"></div>
</body>