简体   繁体   中英

Can't trigger click event on a link

My problem is that I got 2 aspx controls generated like this :

<a id="sortByDate" href="javascript:__doPostBack('sortByDate','')">Date</a>
<a id="sortByLastName" href="javascript:__doPostBack('sortByLastName','')">Last name</a>

so those links allow you to sort the results. I'm trying to put this in a combobox instead of using links.

So I made it like this

<select id="sortBySelect" onchange="javascript:sortBy(this);">
       <option value="sortByLastName">Last name</option>
       <option value="sortByDate">Date</option>
</select>

with this javascript function

function sortBy(sel) {
    var id = sel.value;
    $("#" + id).trigger("click");
}

So when you change the selected element in the combobox I want to trigger the click event on the link to call the dopostback to sort.

It does nothing so far. I tried "click", "onclick", "onClick" and nothing works. Unfortunately, this is for IE quirks mode.

I know, this is really not elegant, but I'm really short in time and I need something quick and dirty. I will make an aspx control eventually to handle this nicely.

Any ideas how I could make this work in ie quirks mode?

Thank you

尝试更改页面的位置:

document.location = $("#" + id).attr('href');

why don't you just fire the __doPostBack directly:

function sortBy(sel) {
    var id = sel.value;
    __doPostBack(id,'');   
}

Use:

function sortBy(sel) { var id = sel.value; alert($("#" + id).length);//just for conforming that the element exists. $("#" + id).click(); }

Actually, jQuery only triggers any event bound to an element. You are trying to call the href action.

If you don't want to change the markup, you could try this solution .

Otherwise, you will have to change your html markup to bind javascript events & then try triggering it.

Good luck!

Everything works as intended!

JSFiddle proof.

Make sure you have an element with the id sortById and sortByLastName !


JavaScript/jQuery

$(document).ready(function(){
    $('#sortByDate').click(function(){
        alert('Sort By Date Click Event fired!');
    })
});
function sortBy(sel) {
    var id = sel.value;
    $("#" + id).trigger("click");
}

Alternative

Force the window.location change

JavaScript/jQuery

function sortBy(sel) {
    var id = sel.value;
   window.location =  $("#" + id).attr('href');
}

Note: You won't see any change in JSFiddle:

Refused to display 'https://www.google.ca/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM