如何更改目标<a> with a variable</a>

时间:2013-03-13 14:10:59

标签: javascript jquery variables hyperlink

所以我使用jQuery来改变内容 <a href="#" id="aX">的内容为 <a href="#qX"> 点击后者时。

我的工作正常,但我希望这可以与每个链接一起使用,以便#q1仅影响#a1的内容,而#q2仅影响#a2。 我试图用变量传递它,但它不起作用。 我做错了什么?

var echoPick;

$('#q1 a').click(echoAnswer, function () {
    pickID = '#a1';
});

$('#q2 a').click(echoAnswer, function () {
    pickID = '#a2';
});

var pickID;

function echoAnswer() {
    var yourPick = $(this);
    echoPick = yourPick.text();
    $(pickID).text(echoPick);
}

4 个答案:

答案 0 :(得分:4)

不要为每个唯一ID反复重复相同的代码,请尝试以下方法:

HTML: <a href="#" id="aX"><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);
});

[编辑]:为了完整起见 - 如果链接的内容包含HTML标记,并且您希望将其克隆,请使用.html()代替.text();)

请参阅此处的小提琴 - http://jsfiddle.net/teddyrised/c69P6/

答案 1 :(得分:1)

看看这个小提琴: http://jsfiddle.net/H6j6g/1/

$("a[id^=q]").click(function(){
    $("#a" + this.id.substring(1)).text($(this).text());
})

$("a[id^=q]")将选择ID为以字母“q”开头的所有链接。然后,它找到具有相同数字的id的元素,而是以字母“a”开头,并用链接的文本替换该链接的文本。

答案 2 :(得分:0)

试试这个:

$('#q1 a').click(function () {
    $('#a1').text($(this).text());
});
$('#q2 a').click(echoAnswer, function () {
    $('#a2').text($(this).text());
});

答案 3 :(得分:0)

这是一个无关心链接的解决方案

e.preventDefault()也会阻止链接进入任何地方

DEMO

$("a").on("click",function(e) {
  var href = this.href.split("#")[1];

  if (href.indexOf("q") == 0 ) {
    var id = href.replace("q","a");
    $("#"+id).text($(this).text())
    e.preventDefault();
  }
});