单击<a> tag

时间:2015-05-09 13:30:06

标签: jquery html css

I am having trouble activating an input field.

What I want:

  1. Users have scrolled down over the site and want to go back to the top
  2. User clicks "sign up" from the menu bar
  3. It scrolls to the landing page
  4. The input field on the landing page is focused, indicating this is where they sign up

It's number 4 I can't figure out how to do. I've found solutions for clicking labels and buttons, but the "sign up" in the menubar is an a-tag.

So basically: how do I activate the input field when clicking on an a-tag in the menu?

These are the two elements:

                <a id="signup-nav" class="navbar-brand page-scroll" href="#page-top" >Sign up</a>

                    <form class="pure-form fadescript">
                    <fieldset>
                        <legend>Notify me on launch</legend>

                        <input type="email" placeholder="Email me when it is ready">

                        <button type="submit" class="pure-button pure-button-primary">Send</button>
                    </fieldset>
                </form>

Thanks

2 个答案:

答案 0 :(得分:1)

我建议 - 假设它是您要关注的电子邮件字段 - 以下内容:

// binding a click event-handler to the element with
// the id of "signup-nav", using the on() method:
$('#signup-nav').on('click', function() {
  // selecting the relevant input, of type=email,
  // focusing that element (if the selector returns multiple
  // elements the *last* of those elements will be focused:
  $('input[type=email]').focus();
});

$('#signup-nav').on('click', function() {
  $('input[type=email]').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="signup-nav" class="navbar-brand page-scroll" href="#page-top">Sign up</a>

<form class="pure-form fadescript">
  <fieldset>
    <legend>Notify me on launch</legend>

    <input type="email" placeholder="Email me when it is ready">

    <button type="submit" class="pure-button pure-button-primary">Send</button>
  </fieldset>
</form>

顺便说一句,我选择不使用event.preventDefault(),因为你 - 大概 - 仍然想要滚动到特定位置;虽然即使默认操作被阻止,但在大多数浏览器中,将<input>聚焦仍然会将聚焦元素移动到浏览器视口的可见部分。所以它几乎是可选的。

参考文献:

答案 1 :(得分:0)

由于您使用的是anchor元素,因此您可能希望event.preventDefault Docs 而不是.focus()你的输入元素:

http://jsbin.com/neweqa/1/edit?html,css,js,output

$("[href=#page-top]").on("click", function( e ){
  e.preventDefault();
  $(":input[type=email]").focus();
});