属性は必要ありませんonlick
。jQuery を使用して目立たないようにイベント ハンドラーをアタッチするだけです。<a>
また、タグをネストしないでください。
function accept( id ) {
$.post( "/accept/", function ( json ) {
alert( "Was successful?: " + json[ 'success' ] );
} );
}
function addClickHandlers() {
$( ".accept" ).on( 'click', function ( event ) {
event.preventDefault();
accept( /\d+$/.exec( event.target.id )[0] );
} );
}
$( document ).ready( function () {
addClickHandlers();
// If you really mean to call this at this point:
accept();
} );
<table class="table table-condensed" style="margin-top:10px;">
<tbody>
{% for request in conReqs %}
<tr>
<td>
<a href="#{{ request.id }}" class="accept"><img src="{{ MEDIA_URL }}{{ request.creator.username }}Accept</a> · <i class="icon-thumbs-down"></i> <a href="#">Hide</a></p>
</td>
</tr>
{% endfor %}
</tbody>
</table>
イベント処理
HTML:
<a href="" id="some-link">Some link</a>
JS:
$( document ).ready( function () {
// Select element(s). In this case, the one element with the ID
// "some-link". Call `on()` on the selected elements to register an
// event listener, in this case for the `click` event. The second
// argument to `on()` is the handler function, which will be called
// when the event occurs and will be passed a jQuery Event object.
$( "#some-link" ).on( 'click', function ( event ) {
// This prevents the default action associated with the event on
// the target element. In the case of a click event on an
// `a[href]` element, the default action would be to load the URL
// that the `href` resolves to.
event.preventDefault();
// One of the properties of the Event object is `target` -- the
// element that the event occured on. In this case the target will
// be an `a[href]` element, so I can read `event.target.href`. If
// the `a` element had nested elements, `event.target` could be
// the nested element. In that case, you could do
// `$( event.target ).closest( "a" )` to make sure you get the `a`
// element that the event occured within.
// Here I'm running a regular expression on `event.target.href` to
// get a sequence of digits at the end.
var id = /\d+$/.exec( event.target.href )[0];
} );
} );
あなたの質問のユースケースでは、コードは次のように要約できます。
$( document ).ready( function () {
$( ".accept" ).on( 'click', function ( event ) {
event.preventDefault();
var id = /\d+$/.exec( event.target.href )[0];
$.post( "/accept/", { id : id }, function ( json ) {
// ...
} );
} );
} );