Program Tip

JavaScript를 사용하여 ID가있는 td에 텍스트를 삽입하는 방법

programtip 2020. 11. 20. 09:27
반응형

JavaScript를 사용하여 ID가있는 td에 텍스트를 삽입하는 방법


간단한 일이라는 건 알지만 알아낼 수는 없습니다. JavaScript 함수 onload 이벤트에서 오는 일부 텍스트를 td에 삽입하려고합니다.

<html>
 <head>
  <script type="text/javascript">
   function insertText ()
   {
       //function to insert any text on the td with id "td1"
   }
  </script>
 </head>
 <body onload="javascript:insertText()">
  <table>
   <tr>
    <td id="td1">
    </td>
   </tr>
  </table>
 </body>
</html>

도움이 필요하세요?


<html>

<head>
<script type="text/javascript">
function insertText () {
    document.getElementById('td1').innerHTML = "Some text to enter";
}
</script>
</head>

<body onload="insertText();">
    <table>
        <tr>
            <td id="td1"></td>
        </tr>
    </table>
</body>
</html>

다음과 같이 텍스트 노드를 추가하십시오.

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

몇 가지 옵션이 있습니다 ... TD를 찾았다 고 가정하면 다음과 같이 var td = document.getElementyById('myTD_ID');할 수 있습니다.

  • td.innerHTML = "mytext";

  • td.textContent= "mytext";

  • td.innerText= "mytext";-이것은 IE 외부에서 작동하지 않을 수 있습니까? 확실하지 않다

  • 이전 포스터가 언급 한대로 firstChild 또는 children 배열을 사용하십시오.

텍스트 만 변경해야하는 경우 textContent가 더 빠르고 XSS 공격에 덜 취약합니다 ( https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent )


<td>비어 있지 않은 경우 인기있는 트릭 중 하나는 중단되지 않는 공백을 삽입하는 &nbsp;것입니다.

 <td id="td1">&nbsp;</td>

그러면 다음을 사용할 수 있습니다.

 document.getElementById('td1').firstChild.data = 'New Value';

Otherwise, if you do not fancy adding the meaningless &nbsp you can use the solution that Jonathan Fingland described in the other answer.


Use jQuery

Look how easy it would be if you did.

Example:

$('#td1').html('hello world');

참고URL : https://stackoverflow.com/questions/2163558/how-to-insert-text-in-a-td-with-id-using-javascript

반응형