Why does this HTML never trigger this jQuery function?
I did not define showprayer
as a class in my CSS stylesheet.
Is that the reason this jQuery function is never called for the HTML below?
$('.showprayer').click( function(event)
{
console.log("showprayer");
$.post('/show_prayer', { 'name' : $(this).text() }, function(data)
{
//... do something with 开发者_高级运维the data returned from the post
});
});
<a href="#" id="showprayer_106" class="showprayer">
<tr id="prayer_106" >
<td>Prayer <span class="prayerspn" id="prayerspn_106">106</span></td>
<td>03/19/1968</td>
</tr>
</a>
I'm trying to pass the prayerId
(in this case 106
to the /show_prayer
handler. There's probably a simpler way to do it but the easiest way I can think of is to put it inside the span above:
<span class="prayerspn" id="prayerspn_106">106</span></td>
And then pull the text ("106"
) out of the span and pass it in the $.post
call.
The HTML is invalid. <tr>
elements may not be children of <a>
elements. Whatever your browser is doing to try to recover from the error probably ends up with the <a>
element being empty and thus not having any clickable pixels.
Always validate your markup.
The URI "show_prayer" strongly suggests that this function is all about getting and displaying information. If it is, then a link is the right choice (but you should change the JS so it makes a GET request instead of a POST request), otherwise you should be looking at using a form instead.
Assuming that a link is the right way forward then it should point to something more sensible than the top of the page.
If we apply the above to the code, then we get something like:
<tr id="prayer_106" >
<td><a href="/show_prayer?name=106">Prayer 106</a></td>
<td>03/19/1968</td>
</tr>
You can then apply JS along the lines of:
function handlePrayer(e) {
var uri = jQuery('a', this).attr('href');
jQuery.get(uri, function (data) { /* Do something with the returned data */ };
e.stopPropagation();
return false;
}
jQuery('table.myTable tr').click(handlePrayer);
jQuery will add an HTTP header (X-Requested-With: XMLHttpRequest) that you can use to decide if /show_prayer should return a complete HTML document or just the data you want to process with JavaScript.
精彩评论