简体   繁体   English

获取由Javascript在数据列表中单击的项目的值

[英]Get value of item which is clicked in datalist by Javascript

When design I have a Datalist with a label inside. 设计时,我有一个带有标签的数据列表。 when load it will has 10 label(datasource from list has 10 value type int ). 加载时将具有10个标签(列表中的数据源具有10个值类型int)。 I want get value of any label which i click. 我想获取我单击的任何标签的值。 I think i must resolve 2 problem: 1. Find control(label inside datalist) which is clicked. 我认为我必须解决2个问题:1.找到被单击的控件(数据列表中的标签)。 2. Get value of it. 2.获得价值。

protected void Page_Load(object sender, EventArgs e)
    {
        List<int> list = new List<int>();
        for (int i = 0; i < 10; i++)
        {
            list.Add(i);

        }
        int a=1;

        DataList1.DataSource = list;
        DataList1.DataBind();
        foreach (DataListItem item in DataList1.Items)
        {
            ((Label)item.FindControl("Label1")).Text = a.ToString();
            if ((Convert.ToInt32(((Label)item.FindControl("Label1")).Text)) % 2 != 0)
            {
                ((Label)item.FindControl("Label1")).BackColor = System.Drawing.Color.Gray;
            }
            ((Label)item.FindControl("Label1")).Attributes.Add("onclick", "run();");
            a++;
        }

This is my run() function 这是我的run()函数

function run() {

            $("#Panel1").scrollTop(100*gt1);

        }

Here, i want gt1 get value of label clicked. 在这里,我希望gt1获得单击的标签的值。

Thanks for helping(sr about my English) 感谢您的帮助(有关我的英语的帮助)

Try it this way... 这样尝试吧...

We will pass the current object of label while binding javascript event with it using keyword this. 当使用关键字this将javascript事件与其绑定时,我们将传递label的当前对象。 on server side 在服务器端

((Label)item.FindControl("Label1")).Attributes.Add("onclick", "run(this);");

On Client side we have to change the definition to receive a parameter which is passed from server side. 在客户端,我们必须更改定义以接收从服务器端传递的参数。 In our case parameter name is lbl. 在我们的情况下,参数名称为lbl。

function run(lbl)
{
alert(lbl.innerText);
}

This is nice article will give you good understanding of grid view here 这是很好的文章会给你网格视图的很好的理解这里

You can attach click event more elegantly with any item within datalist using css class instead of defining onclick event for each item. 您可以使用CSS类将click事件更优雅地附加到数据列表中的任何项目,而不必为每个项目定义onclick事件。

eg label have the following css property = "itm"; 例如,label具有以下css属性=“ itm”;

$(document).on('click', '.itm', function (e) {
   run(this);
});

I found how to resolve my problem: 我找到了解决问题的方法:
First add: 首先添加:

string gt = ((Label)item1.FindControl("lblstt")).Text; 字符串gt =((Label)item1.FindControl(“ lblstt”))。Text;

After that: 之后:

((Label)item2.FindControl("lblCauHoi")).Attributes.Add("onclick", "run("+gt+");"); ((Label)item2.FindControl(“ lblCauHoi”))。Attributes.Add(“ onclick”,“ run(” + gt +“);”);

Hope it's useful. 希望它有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM