1
4

4 回答 4

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/

于 2013-03-13T14:22:08.860 回答
1

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.

于 2013-03-13T14:23:04.430 回答
0

Try this:

$('#q1 a').click(function () {
    $('#a1').text($(this).text());
});
$('#q2 a').click(echoAnswer, function () {
    $('#a2').text($(this).text());
});
于 2013-03-13T14:15:13.223 回答
0
于 2013-03-13T14:17:26.223 回答