将数据或数组索引附加到锚标记 [英] Attach data or array index to anchor tag

查看:58
本文介绍了将数据或数组索引附加到锚标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些javascript/jquery代码,可以用一堆列表项动态填充无序列表.在列表项中,我有一个链接,我想将一些数据与该链接相关联,如下所示:

I have some javascript/jquery code that dynamically populates an unordered list with a bunch of list items. In the list items I have a link and I want to associate some data with that link which is generated like so:

var thing1 = { name: 'My Object' };
var thing2 = { name: 'My Other Object' };
var li = $('<li></li><br />');
var aSel = $('<strong>' + thing1.name + '<br /><a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>';
li.append(aSel);
li.append(add);
$('#sidebar').append(li);
//This is in a loop so the same thing would happen with thing2, etc

将生成HTML,如下所示:

would generate HTML like so:

<div id="results">
    <ul id="sidebar">
        <li>
            <strong>My Object</strong><br />
            <a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>
        </li>
        <li>
            <strong>My Other Object</strong><br />
            <a class="btn btn-mini btn-success addDeal" href="javascript:void(0)"><i class="icon-plus"></i>Add Deal</a>
        </li>
    </ul>
</div>

因此,如果用户单击第一个添加交易"链接,我想使用脚本中其他位置的thing1数据.如果他们的第二个链接被单击,我想使用thing2数据.

So if the user clicks the first Add Deal link, I want to work with the thing1 data elsewhere in my script. If they second link is clicked on, I want to work with the thing2 data.

我要走的路径涉及一个数组和一些我觉得不太合适的代码.我想我缺少一些琐碎的东西.

The path I'm going down involves an array and some code that doesn't feel quite right to me. I figure I'm missing something trivial.

推荐答案

您可以使用 jQuery.data 函数可将事物"附加到每个链接.在var aSel =行之后:

You can use the jQuery.data function to attach a "thing" to each of your links. Right after the var aSel = line:

$('a', aSel).data('thing', thing1); // Select the anchor tag inside of 
                                    // aSel and attach thing1 to it

然后,在单击锚标记后,使用以下命令对其进行检索:var thing = $(this).data('thing');

Then when the anchor tag is clicked, retrieve it with: var thing = $(this).data('thing');

这篇关于将数据或数组索引附加到锚标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆