您不需要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) {
// ...
});
});
});
來源
2012-08-05 21:19:08
JMM
感謝您的回答訪問ID後!我接受一個錯誤(/ \ d + $/.exec(event.target.id)[0]); Uncaught TypeError:無法讀取屬性'0'爲空:8000 /:43 (匿名函數):8000 /:43 jQuery.event.dispatch jquery.js:3332 jQuery.event.add.elemData.handle .eventHandle – Mohammed 2012-08-05 21:44:11
我會''console.log(event.target.id)'在該行之前,看看你有什麼。你是否像我建議的那樣設置了HTML:''? – JMM 2012-08-05 22:03:43
對不起,我的錯誤顯而易見。我把錯誤的屬性放在代碼中:'id'當它應該是'href'時。我更新了代碼以糾正錯誤。我還沒有得到你的原始代碼那麼遠,但作爲@ dm03514指出,你顯然需要發送必要的數據到服務器,所以如果這最終成爲最關鍵的事情顯然他的答案應該被我的接受,但我仍然建議你加入我的建議 - 不要嵌套''標籤,並且不加引人注目地附加事件處理程序。 – JMM 2012-08-05 22:05:38