[英]jQuery - trigger a custom event on a link
I am trying to run this custom 'getOffer()' event using jQuery 我正在尝试使用jQuery运行此自定义'getOffer()'事件
<a href="javascript: void getOffer();" title="Submit for offer"><img src="images/img.jpeg"></a>
I have tried the following but it doesn't seem to work (I am using the Firefox Firebug console.log window) 我已经尝试了以下操作,但似乎不起作用(我正在使用Firefox Firebug console.log窗口)
$('a[title="Submit for offer"]').trigger('getOffer');
This is the page I am trying this on: http://bit.ly/1dpIMFk Can anyone suggest any ideas? 这是我正在尝试的页面: http : //bit.ly/1dpIMFk有人可以提出任何想法吗?
<a href="javascript: void getOffer();" title="Submit for offer"><img src="images/img.jpeg"></a>
$(document).ready(function(){
$('a[title="Submit for offer"]').trigger('getOffer');
});
function getOffer(){
alert('link clicked');
}
Seems working fine for me.I think you didnt wrapped your event trigger in document ready. 似乎对我来说工作正常。我认为您没有将事件触发器包装在准备好的文档中。 DEMO
DEMO
您可以使用
<a href="#" onClick="getOffer();"><img src="images/img.jpeg"></a>
Creating an custom event on jQuery 在jQuery上创建自定义事件
First add some identifier (id/class) to your link 首先向您的链接添加一些标识符(ID /类)
<a id="linkOffer" title="Submit for offer"><img src="images/img.jpeg"></a>
Then, create your CUSTOM event. 然后,创建您的CUSTOM事件。
//The function that will to the getOffer things
function getOffer() {
//Do get offer...
}
$(document).ready(function(){
//Custom event pointing to the function
$('a#linkOffer').on('getoffer',getOffer);
//Default click event
$('a#linkOffer').on('click',function(e){
//Do click stuff.
//Trigger your custom event.
$(this).trigger('getoffer');
//If you wish to not move the page, prevent the default link click behavior (moveing to other page)
e.preventDefault();
});
});
Trigger will not function because it search click
attribute in element. 触发器将不起作用,因为它会搜索元素中的
click
属性。 Work around for this can be is: 解决方法可以是:
Add click attribute to the element and then call the jquery function. 将click属性添加到元素,然后调用jquery函数。
<a href="javascript: void getOffer();" title="Submit for offer"></a>
<button value="yu" onclick="getOffer();"/>
<script>
$("a[title='Submit for offer']").attr("onclick",$("a[title='Submit for offer']").attr('href')); // get value from href
$("a[title='Submit for offer']").trigger('click');
function getOffer()
{
alert('j');
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.