简体   繁体   English

jQuery选择器中的字符串串联

[英]string concatenation inside jquery selectors

I am developing a application in C#, ASP.NET and I have a lot os divs in my page, each div is a container for a chat message and each div have a unique id: like this 我正在用C#,ASP.NET开发应用程序,并且页面中有很多os div,每个div是一个聊天消息的容器,每个div都有一个唯一的ID:

"<div id='" + myMsgs[j].id_chat_message + "' style='padding: 10px;'>"

so, each div have the same id in page and in database. 因此,每个div在页面和数据库中都有相同的ID。

now a want to find some div, with jquery, but it doesnt work 现在想用jQuery查找一些div,但是不起作用

        for (var j = 0; j < myMsgs.length; j++) {
        findDiv = $('#<%= ' + myMsgs[j].id_chat_message + '.ClientID%>');
    }

i know that my problem is the concatenation of the strings, but i dont know how to solve it. 我知道我的问题是字符串的串联,但是我不知道如何解决它。

According to your code "myMsgs" should be something like this (in javascript): 根据您的代码,“ myMsgs”应如下所示(在javascript中):

var myMsgs = [{"id_chat_message":"id1"},{"id_chat_message":"id2"},{"id_chat_message":"id3"}];

Which would mean this will let you get at the divs you want: 这意味着您可以进入所需的div:

for(var j = 0, l = myMsgs.length; j < l; ++j){
    $("#" + myMsgs[j].id_chat_message);
}

But there is probably a better way to do what you want. 但是可能有更好的方法来做您想要的事情。

Can you provide some more details? 您能否提供更多详细信息?

the simplest approach would be: add a class -property, which you can then access via jQuery - eg. 最简单的方法是:添加一个class -property,然后可以通过jQuery访问class -例如。

var messageBoxes = $('.mySpecialCssClass');

you can now iterate over this array and do something with jQuery/javaScript! 您现在可以遍历此数组,并使用jQuery / javaScript做一些事情!

When you try to use server tags in the aspx page like that, you are telling ASP .NET to process the page during rendering and replace all those tags with their corresponding values or evaluations. 当您尝试在aspx页面中使用服务器标记时,您是在告诉ASP .NET在呈现过程中处理该页面,并将所有这些标记替换为其相应的值或评估。 Since you're trying to build the string inside the server tags dynamically using JavaScript, ASP .NET isn't going to process that string and you'll end up with code like this: 由于您尝试使用JavaScript在服务器标签内动态构建字符串,因此ASP .NET不会处理该字符串,并且最终会得到如下代码:

$("#<%=id1.ClientID %>")

ASP .NET only processes this type of tag when it renders the page (which is already finished), and this is running on the client-side only, so this isn't going to work. ASP .NET仅在呈现页面(已完成)时才处理这种类型的标记,并且该标记仅在客户端上运行,因此无法正常工作。

You should be able to just do this: 您应该能够做到这一点:

for (var j = 0; j < myMsgs.length; j++) {
  findDiv = $('#' + myMsgs[j].id_chat_message);
}

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

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