4 回答
Instead of repeating the same code over and over again for each unique ID, try this:
HTML:
<a href="#" id="aX">
and <a href="#qX">
JS:
// Select for all links that start with "#q(...)"
$("a[href^='#q']").click(function(e) {
// Prevent default
e.preventDefault();
// Define some variables
var x = $(this).attr("href").substr(2),
content = $(this).text();
// Select the correct element to replace text
$("#a" + x).text(content);
});
[Edit]: For the sake of completeness - should the content of the link contain HTML tags and you would like to clone them over, use .html()
instead of .text()
;)
See fiddle here - http://jsfiddle.net/teddyrised/c69P6/
Take a look at this fiddle: http://jsfiddle.net/H6j6g/1/
$("a[id^=q]").click(function(){
$("#a" + this.id.substring(1)).text($(this).text());
})
$("a[id^=q]")
Will select all links with IDs starting with the letter "q". Then it finds the element with an id with the same number but instead starts with the letter "a" and replaces that link's text with the text of the link that was clicked.
Try this:
$('#q1 a').click(function () {
$('#a1').text($(this).text());
});
$('#q2 a').click(echoAnswer, function () {
$('#a2').text($(this).text());
});