在Jquery中定义一个按钮的onclick事件

时间:2013-09-11 12:10:48

标签: javascript jquery button onclick

我有一个<button>,以便在点击时将页面滚动到特定的DIV(#contact

<button onclick="location.href='#contact';">Click Me</button>

如何在Javascript中定义它?

$('button[onclick^="#"]').on('click',function (e) {
// Some stuffs here...
});

我正在使用它来设置从button到DIV的滚动动画:

$('a[href^="#"]').on('click',function (e) {
.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});

但它仅适用于a href因为a[href^="#"]。所以我有兴趣让它适用于我的<button>

5 个答案:

答案 0 :(得分:1)

定义按钮

<button class="jumper" data-href="#contact">Click Me</button>

附加点击事件。

$('button.jumper').click(function (e) {
    // new location
    location.href= $(this).data().href;
});

答案 1 :(得分:0)

您也可以使用锚标记<a>

来执行此操作
Top <a href="#bottom">Go to Bottom</a>

<div id="bottom">
Bottom
</div>

参考上面的示例代码

答案 2 :(得分:0)

<强> HTML

<button id="clicker" onclick="location.href='#contact';">Click Me</button>

<强> JQuery的

$('#clicker').click(function (e) {
  $.scrollTo($('#somediv'), 300);
});

答案 3 :(得分:0)

的jQuery

按钮' s

$('button[onclick^="location.href=\'#"]').on('click',function (e) {
 e.preventDefault();
 var target = this.hash,
 $target = $(target);
 $('html, body').stop().animate({
  'scrollTop': $target.offset().top
 }, 900, 'swing', function () {
  window.location.hash = target;
 });
});

一种 jQuery方法,用于获取包含值为'location.href =#'的点击事件的按钮

$('button[onclick^="location.href=\'#"]').on('click',function (e) {
 // Some stuffs here...
}

在javascript中查找/创建按钮和定义onclick事件的方法:

搜索第一个按钮(注[0])

document.getElementsByTagName('button')[0].onclick=function(){
 location.href='#contact';
}

按ID获取按钮(注意'myButton')

document.getElementById('myButton').onclick=function(){
 location.href='#contact';
}

动态创建整个按钮并将其添加到正文

var button=document.createElement('button');
button.onclick=function(){
 location.href='#contact';
}
document.body.appendChild(button);

找到按钮的现代方法

var button=document.querySelector('button');

var button=document.querySelectorAll('button')[0];

B 纯javascript方式获取包含值为'location.href =#'的点击事件的按钮

var buttons=document.querySelectorAll('button[onclick^="location.href=\'#"]');

非ie事件

button.addEventListener('click',function(){
 location.href='#contact';
},false);

即事件

button.attachEvent('onclick',function(){
 location.href='#contact';
});

有任何问题吗?

答案 4 :(得分:0)

试试这个:

<强> HTML:

<input type="submit" value="submit" name="submit" onclick="myfunction()">

<强> jQuery的:

<script type="text/javascript">
 function myfunction() 
 {
    // do whatever you want
 }
</script>