简体   繁体   English

如何在javaScripts中获取动态元素的InnerText

[英]How to get InnerText of Dynamic elements in javaScripts

I have been struggling with is one for 2 days now.我一直在为一个 2 天而苦苦挣扎。 I have seen many somewhat similar questions here like This One which was the closest so far but couldn't figure something out of it.我在这里看到了很多类似的问题,比如This One ,这是迄今为止最接近的问题,但无法从中找出一些东西。

Here is what I want:这是我想要的:

I'm generating card dynamically with elements & Button.我正在使用元素和按钮动态生成卡片。 when I click of the generated card's button, I want to retrieve the texts of the elements in that card.当我单击生成的卡片按钮时,我想检索该卡片中元素的文本。

Here is the Origin html Card这是 Origin html 卡片

 <div class="col-12 mb-3" data-aos="fade-up" data-aos-delay="300">
    <div class="row g-0 border theme-border-radius theme-box-shadow p-2 align-items-center theme-bg-white">
        <div class="col-12 col-md-3">
            <div class="d-flex">
                <div class="d-flex flex-column ms-2">
                    <span class="font-small d-inline-flex mb-0 align-middle">Test Name </span>
                    <span class="font-small d-inline-flex mb-0 align-middle">Test Num</span>
                </div>
            </div>
        </div>
        <div class="col-4 col-md-2">
            <div class="fw-bold">Test Time</div>
        </div>
        <div class="col-12 col-md-3 text-center mt-md-0 mt-2">
            <div class="fw-bold"><i class="bi bi-currency-dollar ms-2"></i>Test Cost</div>
            <button type="submit" class="btn-select btn btn-effect">
                <span class="font-small">Select</span>
            </button>
        </div>
    </div>
</div>

Here is the JavaScript Function that dynamically generates the card这是动态生成卡片的 JavaScript 函数

  function TestFunction(parm1, param2, param3) {
            // alert('Function Scripts');
            $("#card").empty();
            var html = "";

            $.ajax({
                type: "POST",
                url: "WebService.asmx/Serverfunction",
                data: "{'param1':'" + param1 + "', 'param2':'" + param2 + "', 'param3':'" + param3 + "'}",
                // data: "{'Destination':'" + Destination + "'}",
                // data: "{'DepDate':'" + DepDate + "'}",
                contentType: "application/json",
                dataType: "json",
                success: function (data) {

                    try {
                        //alert("Testing Filter By Search Function : " + Origin);

                       
                        for (var i = 0; i < data.d.length; i++) {

                            if (data.d[i].TestName != "") {

                                html += " <div class='col-12 mb-3' data-aos='fade-up' data-aos-delay='300'>";
                        html += " <div class='row g-0 border theme-border-radius theme-box-shadow p-2 align-items-center theme-bg-white'>";

                                html += "   <div class='col-12 col-lg-3'>";

                                html += "  <div>";
                                html += "  <span class='font-small d-inline-flex mb-0 align-middle TestName'>" + data.d[i].TestName + "</span> |";
                                html += "  <span class='font-small d-inline-flex mb-0 align-middle TestNum'>"  + data.d[i].TestNum + "</span> ";
                                html += "  </div>";

                                html += "  </div>";

                                html += "  <div class='col-4 col-lg-2'>";
                                html += "  <div class='fw-bold TestTime' id='TestTime"+i+"'>" + data.d[i].TestTime + " </div>";
                                html += "  </div>";

                                html += "  <div class='col-12 col-lg-3 text-center mt-2 mt-lg-0'>";
                                html += "   <div class='fw-bold TestCost'><i class='bi bi-currency-dollar ms-2'></i>" + data.d[i].TestCost + " </div>";
                                html += "   <button id='btn"+i+"' type='submit' class='btn-select btn btn-effect'> <span class='font-small'>Select</span></button>";
                                html += "  </div>";


                                html += "  </div>";
                        html += "  </div>";

                            }
                        }
                       
                        $("#card").append(html)
                    } catch (e) {
                        error(e);
                    }
                },
                error: function (xhr, status, e) { alert(xhr.responseText); }
            });

        }

I call this function in server Side(WebService ) which is working fine.我在服务器端(WebService)调用这个函数,它工作正常。 The Card is generated with regards to the returned records, if it;s 3 records it generated x3 , if its 5 records it generated x5 and so on.卡片是根据返回的记录生成的,如果它有 3 个记录,它生成x3 ,如果它有 5 个记录,它生成x5 ,依此类推。

The problem is retrieving the Texts of these elements in the generated card.问题是在生成的卡片中检索这些元素的文本。 When one the buttons is clicked, I want Insert them into the database.单击其中一个按钮时,我想将它们插入数据库。

I was able to identify which Button was clicked, but based on that, I could figure out awy to get the InnerText/InnerHTML of the elements of that Card.我能够确定单击了哪个按钮,但基于此,我可以弄清楚如何获取该卡片元素的 InnerText/InnerHTML。

Here is one of What I have tried so far.这是我到目前为止尝试过的方法之一。

$(document).on('click', '.btn-select', function(){
            var btnId = $(this).attr('id')
             alert("Cliked on : "+btnId );

            //const testName = $('#btnId').parent.parent.find('.TestName').innerText;
            const testName = $('#btnId').parent.parent.find('.TestName').innerHTML;

             alert(tot);
            alert("Testing");
        });

with gets the clicked button, but I was trying to navigate to the root parent and find the elements by class which apparently is not working, so what could I be doing wrong, what other possible solutions?. with 获取单击的按钮,但我试图导航到根父级并按类查找显然不起作用的元素,那么我可能做错了什么,还有其他可能的解决方案吗? I would appreciate if anyone could me with this one, I'm really stuck.如果有人能帮我解决这个问题,我将不胜感激,我真的被困住了。 This is my first really project with Combinations.这是我第一个真正的组合项目。

I am using Asp.net Webforms with Javascript (WebService) as mentioned earlier, Thanks in advance.如前所述,我正在使用带有 Javascript (WebService) 的 Asp.net Webforms,在此先感谢。

To get the text of the elements in the card when the button is clicked, you can use the.text() method to retrieve the text content of the elements.要在单击按钮时获取卡片中元素的文本,可以使用 .text() 方法来检索元素的文本内容。

Here is an example of how you can achieve this:以下是如何实现此目的的示例:

First, you can give each element in the card a unique class or id, so that you can easily select it using jQuery.首先,您可以为卡片中的每个元素指定一个唯一的类或 ID,以便您可以使用 jQuery 轻松选择它。 For example, you can give the TestName element a class.test-name, and the TestNum element a class.test-num.例如,您可以为 TestName 元素指定一个 class.test-name,为 TestNum 元素指定一个 class.test-num。

Next, you can use the.click() method to attach a click event handler to the button element.接下来,您可以使用 .click() 方法将单击事件处理程序附加到按钮元素。 Inside the event handler function, you can use the $(this) selector to reference the button element that was clicked, and then use the.closest() method to find the parent card element.在事件处理函数内部,您可以使用 $(this) 选择器引用被单击的按钮元素,然后使用 .closest() 方法找到父卡片元素。

Finally, you can use the.find() method to search for the.test-name and.test-num elements within the parent card element, and then use the.text() method to retrieve the text content of these elements.最后,您可以使用.find() 方法在父card 元素中搜索.test-name 和.test-num 元素,然后使用.text() 方法检索这些元素的文本内容。

Here is an example code that demonstrates this:这是一个示例代码,演示了这一点:

$('.btn-select').click(function() {
  var $card = $(this).closest('.theme-bg-white');
  var testName = $card.find('.test-name').text();
  var testNum = $card.find('.test-num').text();

  console.log(testName, testNum);
});

I hope this helps.我希望这有帮助。 Let me know if you have any questions.如果您有任何问题,请告诉我。

Hum, do you really need all that javascript and making web calls?嗯,你真的需要所有的 javascript 和进行网络调用吗?

In most cases, you better off to just create a div, and float it (so the web layout becomes responsive), and that quite much it.在大多数情况下,您最好只创建一个 div,然后将其浮动(这样 Web 布局就会响应),仅此而已。

So, anytime (at least in web forms land), you better off to layout the ONE thing you want "one time", and then if you want it to repeat?所以,任何时候(至少在网络表单领域),你最好“一次”布局你想要的一件东西,然后如果你想让它重复?

then surround that "thing" with a repeater.然后用中继器包围那个“东西”。

So, say this layout:所以,说这个布局:

<asp:Repeater ID="Repeater1" runat="server"  >
    <ItemTemplate>                
        <div style="border-style:solid;color:black;width:320px;height:450px;float:left;margin-right:10px;margin-bottom:10px">
            <div style="text-align:center;padding:2px 10px 2px 10px" class="cards" >
                <asp:Button ID="cmdMyView" runat="server" Text="View" 
                    CssClass="btn-info" style="float:right"
                    CommandArgument = '<%# Eval("ID") %>'
                    OnClick="cmdMyView_Click" />
                <br />

                <h3 id="hFighter" runat="server"><%# Eval("Fighter") %></h3>
                <asp:Image ID="Image2" runat="server" 
                    ImageUrl = '<%# Eval("ImagePath") %>' Width="170" />
                <h4>Engine</h4>
                <asp:Label ID="EngineLabel2" runat="server" Text='<%# Eval("Engine") %>' />
                <h4>Description</h4>
                <asp:Label ID="DescLabel" runat="server" Text='<%# Eval("Description") %>' />
                <br /> 
            </div>
        </div>

        </ItemTemplate>
</asp:Repeater>

Now, with a repeater, then we don't need javascript, we don't have messy server side code or methods, and we don't have client side javascript messy code either.现在,有了中继器,我们就不需要 javascript,我们没有凌乱的服务器端代码或方法,我们也没有客户端 javascript 凌乱的代码。

Code behind is thus:因此,后面的代码是:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not IsPostBack Then
        LoadData()
    End If

End Sub

Sub LoadData()

    Using conn As New SqlConnection(My.Settings.TEST4)
        Dim strSQL As String =
            "SELECT * FROM Fighters"

        Using cmdSQL As New SqlCommand(strSQL, conn)
            conn.Open()
            Dim rstData As New DataTable
            rstData.Load(cmdSQL.ExecuteReader)
            Repeater1.DataSource = rstData
            Repeater1.DataBind()
        End Using
    End Using

End Sub

And we now see/get this card type viewer:我们现在看到/得到这个卡片类型的查看器:

在此处输入图像描述

And if we re-size the page, then it changes the layout quite nice, since we floated those divs.如果我们重新调整页面大小,那么它会很好地改变布局,因为我们浮动了那些 div。

And why the above suggestion?为什么要提出上述建议?

Well, then note the code for the button click, it also rather easy, and thus is this:好吧,然后注意按钮点击的代码,它也很简单,因此是这样的:

Protected Sub cmdMyView_Click(sender As Object, e As EventArgs)

    Dim btn As Button = sender
    Dim rRow As RepeaterItem = btn.NamingContainer

    Debug.Print("Row index = " & rRow.ItemIndex)
    Debug.Print("DATA ID pk = " & btn.CommandArgument)
    Dim hFighter As HtmlGenericControl = rRow.FindControl("hFighter")
    Debug.Print("Fighter name = " & hFighter.InnerText)

End Sub

Output of a button click:单击按钮的输出:

Row index = 4
DATA ID pk = 5
Fighter name = Lockheed SR-71 Blackbird

Note how little wiring up and work and effort this was.请注意,这是多么少的接线、工作和努力。 In fact, it was so very little effort that I was able to cook up, post and write an working example for this post!事实上,我只需要很少的努力就可以为这篇文章编写、发布和编写一个工作示例!

So, unless some real compelling reason exists to "inject" a bunch of markup into the page, in most cases, you can use say a repeater, or datalist or some other type of control to "repeat" the markup for you over and over.因此,除非存在某些真正令人信服的理由将一堆标记“注入”到页面中,否则在大多数情况下,您可以使用重复器、数据列表或其他类型的控件来为您一遍又一遍地“重复”标记.

Not only does this elminate a lot of messy code, but MORE bonus points is then note how easy the row button click becomes - we can get the row index, and pluck/pull/get information about each repeated item with far greater ease, and so far, we not had to create expensive web methods, not had to write expensive JavaScript code, and as noted, the bonus part is the ability to get information about the "one thing" we clicked on.这不仅消除了很多混乱的代码,而且更多的奖励点是然后注意单击行按钮变得多么容易 - 我们可以获得行索引,并且可以更轻松地提取/拉取/获取有关每个重复项目的信息,并且到目前为止,我们不必创建昂贵的 Web 方法,也不必编写昂贵的 JavaScript 代码,并且如前所述,好处是能够获取有关我们单击的“一件事”的信息。

So, while a lot of platforms suggest/use/force/normally often have looping code and code to inject the markup, in webforms, in most cases, you don't need all that extra code, looping, and wiring up of code.因此,虽然许多平台建议/使用/强制/通常有循环代码和代码来注入标记,但在网络表单中,在大多数情况下,您不需要所有这些额外的代码、循环和代码连接。 as above shows, we did not even write ONE loop to repeat the information.如上所示,我们甚至没有写一个循环来重复信息。

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

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