没有href、onclick等的按钮

buttons with no href, onclick etc

本文关键字:按钮 onclick href 没有      更新时间:2023-09-26

最近,我看到很多网站的html代码中没有任何hrefs或onclick的可点击对象。我还尝试提醒他们的href、onclick、onmousedown、onmouse up属性,但它只显示"未定义"。我确实注意到这些页面中有很多复杂的javascript。

有一个网站让我特别困惑:http://www.sharenator.com/Boy_Teaches_His_Puppy_How_to_Eat/#/doggy_01_Boy_Teaches_His_Puppy_How_to_Eat-0.html

它实际上相当不错。按钮也无法选择。按钮的id为nextBtn、nextBtn2、prevBtn和prevBtn2。

有人知道如何实现这一点吗?

您可以使用jQuery的.click(回调)函数(http://api.jquery.com/click/)或.delete(selector,'click',callback)(在jQuery 1.7之前)和.on('click],selector、callback)或.bind('click',callcall)。

感谢Anthony Grist指出.live()现在已被弃用:)

因此:

<button id="clickable">Click Me!!</button>

然后用jQuery:瞄准按钮

$("#clickable").click(function(){
    // Send user to this link
    location.href = "http://www.takemehere.com";
});

你可以在我提供的链接和jQuery的主页上阅读更多关于这方面的信息。

更新

实际页面使用处理此问题

$('#prevBtn').mousedown (onBackward);

哪一个会在停机时调用:

function onBackward () {
    showImg (currentId - 1);
}

使用箭头键:

 $(document).keyup (function (event) {
    var activeElement = document.activeElement.tagName;
    if (activeElement == 'INPUT' || activeElement == 'TEXTAREA') return;
    //alert (window.location.pathname);
    if (event.keyCode == 39) onForward();
    else
    if (event.keyCode == 37) onBackward();
});

请参阅http://www.sharenator.com/js/slideshow.js幻灯片的源代码。

您可以尝试使用jQuery ui库-这可以按照您指定的方式创建按钮。

jQuery UI

事件处理程序可能使用Javascript框架(如jQuery)绑定。它们不使用DOM元素的onclick属性。有关使用jQuery将click事件处理程序绑定到按钮的示例,请参阅此jsFiddle,然后单击该按钮以查看该按钮的onclick值(在FF 9中显示为null)。

使用javascript,找到元素并为其提供onClick事件处理程序。例如:

var myElement = document.body;  // or document.getElementById(...), etc.
myElement.onclick = function(event) {alert(event);}

这将避免在HTML中显示任何内容,这也是您链接的网站的操作方式(没有其他方法可以定义行为……除了深奥的CSS)。

使用javascript。这里有一个例子:

<a id="uniqueId" href="#">Button</a>
<script>
    var button = document.getElementById('uniqueId');
    button.onclick = function(e) {
        alert("clicked!");
    }
</script>

点击函数可以在js中初始化,例如$("#nextBtn").click(function);