Jquery equivalent/ Browser compatibility for e.parentNode.parentNode.childNodes[i].innerText;

会有一股神秘感。 提交于 2019-12-08 12:57:41

问题


I am using the following snippet for updating some textbox value from a table.

          <table>
               <tr>
                <td>
                    ProjectName
                </td>
                <td>
                    Block
                </td>
                <td>
                    .WorkProgressMilestone
                </td>
                <td>
                    Completion
                </td>

                 <td>
                    <span class="sep">
                        <img height="15px" width="20px" src="@Url.Content("~/Content/themes/base/images/Edit.png")" /></span><a
                            href="#" onclick="EditWorkDetails(this);" style="text-decoration: none">Edit</a>
                    <input id="WorkProgressEditID" name="WorkProgressEditID" type="hidden" value="@v.WorkProgressID" />
                </td>
      </tr>
     <tr>..</tr>
 </table>



function EditWorkDetails(e) {
document.getElementById("txtCompletion").value =        e.parentNode.parentNode.childNodes[3].innerText;
}

It works fine for me in IE, but not working in other browsers(Chrome). A notable thing is that the table 'td's and 'tr's don't have Id property to distinguish each other. So I can't use jquery over here. What is the alternative I can follow to make it work in all browsers.


回答1:


try this:

document.getElementById("txtCompletion").value = $(this).parent().parent().children()[3].html();

or

$("txtCompletion").val($(this).parent().parent().children()[3].html());



回答2:


Yyou have two problems:

  1. innerText is not universally supported.
  2. All browsers except IE < 9 (and IE 9 in compatibility modes) include whitespace text nodes in childNodes. IE does not, so tr.childNodes[3] is going to refer to different nodes if you have whitespace between your <td> elements.

The fixes I'd recommend:

  1. Use element.textContent || elem.innerText. This is not perfect but will work fine in most cases.
  2. It looks like you're trying to get the text content of a table cell. If so, you can use the cells property of the table, which is universally supported back to IE 4.

Example code with both fixes:

var td = e.parentNode.parentNode.cells[3];
var tdText = td.textContent || td.innerText;



回答3:


innerText is not supported in all browsers, you might try using jquery or

use .textContent and .innerText based on browser version



来源:https://stackoverflow.com/questions/12635751/jquery-equivalent-browser-compatibility-for-e-parentnode-parentnode-childnodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!