簡體   English   中英

如何在行表中查找div元素並返回值?

[英]How to find a div element inside the row table and return the value?

我有一張表,下面的行被foreach語句循環。 在表格內,您可以看到各種div元素。 我想,並通過點擊一類=“postrep”按鈕返回一類=“divrep”的div元素的一個值。 我在下面嘗試了一些方法,但是它返回空對象,所以我不確定是否得到正確的div元素。

jQuery的:

$(function () {
           $('.postrep').click(function () {
               var findiv = $(this).closest('table').find('div[class="divrep"]');
               alert(findiv.toString());

            });
        });

HTML:

<table id="mytable">  

    <tr >
        <td class="tdstyle" >

  <div style="font-weight:bold;">  @Html.DisplayFor(modelItem => item.name) </div> 

   <p >  @Html.DisplayFor(modelItem => item.comment) </p>
  <p> <input type="button" id="like" name="like" value="Like" style="color:blue;border:0px;background-color:inherit;cursor:pointer" /> <input type="button" class ="Reply" name="Reply" value="Replie(s)" /></p>                                                                                                                                 
  <div id="divReply" class ="divrep"> I want to return this string value...

     <div> 
        <div class="editor-field" style="display:none; margin-bottom:5px;margin-top:5px">  
          <input type="text" id="comidvalue" name="id" class="id" value="@Html.DisplayFor(modelItem => item.Id)" />
        </div>

        <br />
        <input type="text" id="namerep" name="name" class="name" style="width:445px;resize:none" />

       <br />
       <textarea id="reply" name="reply" class="reply" style="width:445px;height:100px;resize:none" ></textarea>

         <br />

        <input type="button" class="postrep" value="Post Reply" name="butname" style="cursor:pointer" /> 
      </div>
            <br />

  </div>

        </td>       
    </tr>

</table>

嘗試使用.contents()來獲取文本節點以及子元素,並從返回的集合中獲取第一個元素,

$('.postrep').click(function () {
    var findiv = $(this).closest('.divrep');
    alert(findiv.contents()[0].nodeValue);
});

建議在finddiv對象上使用.text() ,但是如果假定在finddiv有更多文本節點,則首選此解決方案。

演示

那這樣呢

        $(function () {
           $('.postrep').click(function () {
               var findiv = $(this).closest('.divrep');
               alert(findiv.html());

            });
        });

嘗試小提琴只是將api更改為

alert(findiv.text());

希望能幫助到你

對於選擇帶有divrep類的潛水,選擇器為“ .divrep”,並且在每個返回的內容中,如果要使用內部html,則必須使用api html;如果您不想將內容作為簡單文本,則必須使用api 文本

var findiv = $(this).closest('table').find('.divrep');
 alert(findiv.html());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM