3

<button>クリックしたときにページを特定の DIV にスクロールするためにがあります ( #contact)

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

Javascriptでそれを定義する方法は?

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

buttonこれを使用して、 aから 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、そのため、 s でのみ機能しa[href^="#"]ます。だから私はそれを私<button>のもので動作させることに興味があります

4

5 に答える 5

0

jQuery

あなたのボタンのため

$('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;
 });
});

値が「location.href=#」のクリック イベントを含むボタンを取得するjQuery の方法

$('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];

値が「 location.href =#」のクリックイベントを含むボタンを取得する純粋な JavaScript の方法

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

非IEイベント

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

つまり、イベント

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

質問は?

于 2013-09-11T12:31:16.083 に答える
0

これを試して:

HTML:

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

jQuery:

<script type="text/javascript">
 function myfunction() 
 {
    // do whatever you want
 }
</script>
于 2017-08-26T17:11:42.113 に答える