0

我有一个示例代码:

<span id="app_name_1"></span><a onclick="addSelectApplication('name 1');" href="#">Add name 1</a>                   
<span id="app_name_2"></span><a onclick="addSelectApplication('name 2');" href="#">Add name 2</a>               
<span id="app_name_3"></span><a onclick="addSelectApplication('name 3');" href="#">Add name 3</a>

和 javascript

<script>
function addSelectApplication(title) {
    for(var i=0; i<3; i++) {
        parent.document.getElementById('app_name_'+i).innerHTML = title;
    }    
}
</script>

当我点击Add name 1时,结果是

<span id="app_name_1">name 1</span> 
<span id="app_name_2">name 1</span>
<span id="app_name_3">name 1</span>

如何修复结果是:

点击时Add name 1

<span id="app_name_1">name 1</span> 
<span id="app_name_2"></span>
<span id="app_name_3"></span>

点击时Add name 2

<span id="app_name_1"></span>   
<span id="app_name_2">name 2</span>
<span id="app_name_3"></span>
4

4 回答 4

2

您正在遍历所有跨度并设置标题。您需要以某种方式确定您单击了哪一个,这里从标题本身来看:

function addSelectApplication(title) {
    // Extract the link clicked from the title text
    var i = title.replace(/.*(\d)/, "$1");

    // Set the content
    parent.document.getElementById('app_name_'+i).innerHTML = title;
}

干杯

于 2012-11-28T04:40:46.003 回答
0
<span id="app_name_1"></span>   
<span id="app_name_2"></span>
<span id="app_name_3"></span>

<a title="name 1" onclick="addSelectApplication(this);" href="#">Add name 1</a>              
<a title="name 2" onclick="addSelectApplication(this);" href="#">Add name 2</a>             
<a title="name 3" onclick="addSelectApplication(this);" href="#">Add name 3</a>
<script>
    function addSelectApplication(obj) {     
    for(var i=1; i<=3; i++) {        
        var no = obj.title.split(' ');
        if (no[1] == i) {
            document.getElementById('app_name_'+i).innerHTML = obj.title;     
        } else {
            document.getElementById('app_name_'+i).innerHTML = '';     
        }
    }   
    return false;    
}
</script>
于 2012-11-28T05:09:39.247 回答
0

对于您当前的 html 格式,最简单的方法是:

    <span id="app_name_1"></span><a onclick="this.previousSibling.innerHTML = 'name 1';" href="#">Add name 1</a>               
    <br />
    <span id="app_name_2"></span><a onclick="this.previousSibling.innerHTML = 'name 2';"  href="#">Add name 2</a>               
    <br />
    <span id="app_name_3"></span><a onclick="this.previousSibling.innerHTML = 'name 3';"  href="#">Add name 3</a>
于 2012-11-28T04:53:55.497 回答
0

尝试这个

 function addSelectApplication(title)
    {
        var splitStr = title.split(' ');

        for (var i = 1; i < 4; i++)
        {
            if (splitStr[1] == i.toString())
            {
                parent.document.getElementById('app_name_' + i).innerHTML = title;
            }
            else
            {
                parent.document.getElementById('app_name_' + i).innerHTML = "";
            }
        }
    }
于 2012-11-28T04:47:10.527 回答