简体   繁体   English

Javascript根据提交值/名称跳转到锚点

[英]Javascript jump to anchor based on submit value/name

I am working on a page that is basically a long form, with tables of info followed by a submit button after each table.我正在处理一个基本上是长表单的页面,其中包含信息表,每个表后面都有一个提交按钮。

The form submits to itself and changes the info in the tables based on user input.表单提交给自身并根据用户输入更改表中的信息。

What I would like to do is have the page jump to "Section X" if "Submit Button X" is pressed, jump to "Section Y" if "Submit Button Y" is pressed, etc.我想要做的是,如果按下“提交按钮 X”,页面跳转到“X 部分”,如果“提交按钮 Y”被按下,则跳转到“Y 部分”,等等。

I'm currently using this Javascript in the head of the doc to try and accomplish this:我目前正在文档的头部使用此 Javascript 来尝试完成此操作:

<script type="text/javascript">

var anchors = new Array(

<?php 
for($i = 0; $i < 13; $i++) {
    $anchors =  "\"$divTag[$i]\"";
    if($i < 12) {
        $anchors .= ", ";
    }
    echo $anchors;
} ?>

)

function jumpToAnchor() {

    <?php if(isset($_POST["submit_fjw"])) { ?>

    window.location = String(window.location).replace(/\#.*$/, "") +
    "#" + anchors[0];

    <?php } if(isset($_POST["submit_jwl"])) { ?>

    window.location = String(window.location).replace(/\#.*$/, "") +
    "#" + anchors[1];

    <?php } ?>
}

It works... kinda.它有效......有点。 It doesn't jump on the first press of the Submit button, but the second.它不会在第一次按下提交按钮时跳转,而是在第二次按下时跳转。

I'm open to suggestions... less Javascript is better, because my Javascript skills are weak at best.我乐于接受建议...... Javascript 越少越好,因为我的 Javascript 技能充其量很弱。 Could I use a variable tied to the submit button that will pass a value to the PHP script and correctly jump to the right section?我可以使用绑定到提交按钮的变量来将值传递给 PHP 脚本并正确跳转到正确的部分吗?

Have you tried something like this?你有没有尝试过这样的事情?

<form action="thisfile.php#section2" name="form1" ... >
....
</form>

<a name="section2">
<form action="thisfile.php#section3" name="form2" ... >
....
</form>

<a name="section3">
<form ....

when form1 is submitted, file reloads and automaticly goes to anchor named section2, when form2 is submitted, it scrolls to section3, etc当form1提交时,文件重新加载并自动转到名为section2的锚点,当form2提交时,它滚动到section3等

May be you find more convenient to use http://www.w3schools.com/html/html_links.asp (section HTML Links - The name Attribute) instead javascript?您可能会发现使用http://www.w3schools.com/html/html_links.asp(HTML链接部分 - 名称属性)代替 javascript 更方便吗? Just a suggestion.只是一个建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM