您不需要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