jQuery replacement for onclick
I've just recently discovered the power of jQuery. Just a quick question though.
What is a replacement for onclick="DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE')" ?
Is there even a way somehow to pass custom information such as an ID to a jquery onclick? Or do i have to stay with the old fas开发者_StackOverflow社区hioned way?
Thanks a lot!
Adam
I usually use a rel="" for some extra data i might need attached to the button or whatnot.
for example
<input class="btnDelete" rel="34" value="Delete" />
then in jquery
$('.btnDelete').click(function() {
DeleteMethod($(this).attr("rel"));
});
If you stick the ID of the object you want to delete in the rel parameter, you can do it this way:
<script type="text/javascript>
$('a.deleter').click(function(){
if($(this).attr("rel") != ""){
DeleteSomething($(this).attr("rel"));
}
});
</script>
<a href="javascript:void(0)" rel="54" class="deleter">Delete Widget</a>
$(document).ready(function () {
$('#selector').click(function() {
//here goes your onclick code
});
);
Please, post some markup for more help.
Also, you should read the Getting started with jQuery resources, linked in the main page of the library.
In jQuery you would more likely do something like:
$('a').click(function(){
# code here
});
With 'a' being whatever selector you want to use to find the right link.
In response to your comment:
Probably the best way, as someone else mentioned, would be to provide the dynamic data in one of the attributes of the link:
<a rel="{id}" >
$('a').click(function(){
deleteFunction($(this).attr('rel'));
});
Instead of this:
<button onclick="DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE')">
Do this:
<button id="thing">
<script>
$(function() {
$("#thing").click(function() {
DeleteSomething('THE ID NUMBER LOADED IN BY SERVER SIDE');
}
}
<script>
It would much cleaner if you do it this way:
<tag class="someclass" prop1="id from serverside" />
$('.someclass').click(function(){
var prop1 = $(this).attr('prop1');
//DeleteSomething(prop1)
});
Use the server to replace {ID} with the actual ID.
HTML:
<form id="deleter">
<input type="hidden" name="id" value="{ID}" \>
<input type="submit" value="Delete" rel="{ID}" \>
</form>
jQuery:
$('form#deleter input[type="submit"]').click(function() {
var id = $(this).attr('rel');
DeleteSomething(id);
return false;
}
Don't forget to implement the deleting server-side also for people who don't have Javascript enabled!
精彩评论