问题
How can you retrieve the value of the rel attribute of a given link and pass it to the handler?
I have a list of links such that
Link list
<div id='one_answer'>Answer1
<a href="$" class="delete_answer" rel='Answer1'>delete</a>
</div>
<div id='one_answer'>Answer2
<a href="$" class="delete_answer" rel='Answer2'>delete</a>
</div>
<div id='one_answer'>Answer3
<a href="$" class="delete_answer" rel='Answer3'>delete</a>
</div>
These links are generated by the following code. The following value of the rel does not seem to be passed to the handler.
Links generated by PHP
echo ($answer . "<a href='#'"
. "class='delete_answer'"
. " rel='" . $body . "'" // I identify the answer
// by the body of the answer
// in the database
. ">delete</a>"
);
The user clicks the second link. The rel attribute should pass the answer to the handler. jQuery should perform the following action based on the POST -data.
jQuery
jQuery('a.delete_answer').live('click', function(){
jQuery.post('/codes/handlers/delete_an_answer.php',
{ delete_answer: jQuery(this).attr('rel') },
function(){
$("#one_answer").removeClass("yellow");
})
});
The file delete_an_answer.php
$dbconn = pg_connect("host=localhost port=5432 dbname=masi user=masi password=123");
// remove the answer
$result = pg_query_params ( $dbconn,
'DELETE FROM answers
WHERE answer = $1',
array ($_POST['answer'] ) // Problem here, because
// $_POST['answer'] is empty when it gets here
// so no answer is deleted
);
I fetch answers from Postgres and put at the same time the value of the rel attribute to be $body.
回答1:
I can see several problems with this code:
- You have more than one
<div id='one_answer'>. IDs should be unique, so$("#one_answer").removeClass("yellow");will always select the first div, not all divs. - delete_an_answer.php - In the php you're looking for
$_POST['answer'], but the ajax has{question_id: jQuery(this).attr('rel')}. - The links in your sample don't have a
rel, andhref='$', which is weird. Also<div id='one_answer>is broken, should be another single quote. I assume these are copy-paste problems.
回答2:
Ok, well... To answer your first question, you can get the index of the element that was clicked within the array of elements matching a given selector using jQuery's index() method:
$('a.delete_answer').live('click', function()
{
var index = $("a.delete_answer").index(this);
// index will be 0 for the first matching link,
// 1 for the second, and so on. Do what you will with this...
...
});
As for the rest of your question, I really have no idea what it is you're asking.
来源:https://stackoverflow.com/questions/1350539/to-make-an-action-based-on-the-link-location-by-jquery