简体   繁体   English

将函数中的对象从html发送到后面的代码

[英]Sending an object in a function from html to code behind

Is it possible to send an element from the html to the code behind on event? 是否可以将元素从html发送到on事件背后的代码? like that, for example: 这样,例如:

<td id="id1" onClick="do1(id1)" runat="server"></td>

code behind: 后面的代码:

protected void do1(object sender, EventArgs e,**var x**)
{
    x. Attributes.Add("class", "class1");
}

No, you can't send an element from the html to the code behind the way you wrote above. 不,您不能将html中的元素发送到上面编写方式后面的代码中。 However if you want to add a value for an attribute of a server control (html elements that have the runat="server"), you can. 但是,如果要为服务器控件的属性(具有runat =“ server”的html元素)添加值,则可以。 Please tell us what's the attribute you want to add and I will include the corresponding piece of code. 请告诉我们您要添加的属性是什么,我将包括相应的代码段。

If it were javascript then you can use the "this" keyword: 如果是javascript,则可以使用“ this”关键字:

<td id="id1" onClick="do1(this)"></td>

"this" means "id1". “ this”的意思是“ id1”。 You can also write your function like this: 您还可以这样编写函数:

function do1(){
   var x = document.getElementById("id1");
   //do sth with x
}

If all you need to do in the code behind is add a CSS class, why not do it via javascript? 如果您只需要在后面的代码中添加一个CSS类,为什么不通过javascript呢?

html: HTML:

<td id="id1" onClick="changeClass()"></td>

javascript: JavaScript的:

<script type="text/javascript">
function changeClass()
{
document.getElementById("id1").className = "class1";
}
</script>

If you need to run your method from the codebehind you will have to post back the page for the code to ever get reached. 如果您需要从后面的代码中运行方法,则必须将页面发回,以使代码始终有效。

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

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