development

div 요소에 onload 이벤트를 추가하는 방법은 무엇입니까?

big-blog 2020. 5. 6. 21:54
반응형

div 요소에 onload 이벤트를 추가하는 방법은 무엇입니까?


onload요소에 이벤트를 어떻게 추가 합니까? 사용해도 되나요:

<div onload="oQuickReply.swap();" ></div>

이것을 위해?


아냐, 못해 작동시키는 가장 쉬운 방법은 요소 바로 뒤에 함수 호출을 넣는 것입니다.

예:

...
<div id="somid">Some content</div>
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
...

또는 훨씬 더 나은 것 </body>:

...
<script type="text/javascript">
   oQuickReply.swap('somid');
</script>
</body>

... 따라서 다음 내용이로드되는 것을 차단하지 않습니다.


onload이벤트에만 사용할 수 있습니다 document(body)자체, 프레임, 이미지, 스크립트. 즉, 본문 및 / 또는 각 외부 리소스 에만 연결할 수 있습니다 . div는 외부 리소스가 아니며 본문의 일부로로드되므로 onload이벤트가 적용되지 않습니다.


onerror를 사용하고 src를 사용하지 않고 IMG 요소에서 일부 j를 자동으로 트리거 할 수 있습니다.

<img src onerror='alert()'>

onload 이벤트는 아래 나열된 것과 같은 몇 가지 태그 만 지원합니다.

<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

여기에 onload 이벤트에 대한 참조


이 시도! 그리고 div에서 트리거를 두 번 사용하지 마십시오!

div 태그 전에 호출 할 함수를 정의 할 수 있습니다.

$(function(){
    $('div[onload]').trigger('onload');
});

데모 : jsfiddle


div의로드 이벤트에서 함수를 호출하려는 경우 jQuery를 사용하지 않으려는 경우 (내 경우와 같이 충돌하기 때문에) 모든 HTML 코드 또는 함수 코드를 포함하여 작성한 다른 코드는 단순히 함수를 호출합니다.

/* All Other Code*/
-----
------
/* ----At the end ---- */
<script type="text/javascript">
   function_name();
</script>

또는

/* All Other Code*/
-----
------
/* ----At the end ---- */
<script type="text/javascript">
 function my_func(){
   function definition;      

  }

 my_func();
</script>

iframe을 사용하고 숨 깁니다. iframe은 body 태그처럼 작동합니다.

<!DOCTYPE html>
<html>
<body>

<iframe style="display:none" onload="myFunction()" src="http://www.w3schools.com"></iframe>
<p id="demo"></p>

<script>
function myFunction() {
    document.getElementById("demo").innerHTML = "Iframe is loaded.";
}
</script>

</body>
</html>

HTML 청크 (템플릿 인스턴스)가 삽입 된 후 초기화 코드를 실행해야했으며 템플릿을 조작하고 DOM을 수정하는 코드에 액세스 할 수 없었습니다. html 요소 (일반적으로)를 삽입하여 DOM을 부분적으로 수정하는 경우에도 동일한 아이디어가 적용 <div>됩니다.

얼마 전에 나는에 거의 <img>포함되지 않은 onload 이벤트로 해킹을 수행 <div>했지만 범위가 지정된 빈 스타일도 수행한다는 것을 알았습니다 .

<div .... >
<style scoped="scoped" onload="dosomethingto(this.parentElement);" >   </style>
.....
</div>

업데이트 (2017 년 7 월 15 일)- <style>마지막 버전의 IE에서는 온로드가 지원되지 않습니다. Edge는이를 지원하지만 일부 사용자는이를 다른 브라우저로보고 IE를 사용합니다. <img>요소는 모든 브라우저에서 더 잘 작동하는 것 같습니다.

<div...>
<img onLoad="dosomthing(this.parentElement);" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
...
</div>

이미지의 시각적 영향과 리소스 사용을 최소화하려면 이미지를 작고 투명하게 유지하는 인라인 src를 사용하십시오.

내가 a를 사용하는 것에 대해해야한다고 생각하는 한 가지 의견 은 스크립트가 가까운 곳 <script>을 결정 하는 것이 얼마나 어렵다는 것입니다 <div>. 특히 템플릿이 생성하는 각 인스턴스에서 동일한 ID를 가질 수없는 템플릿에서. 나는 대답이 document.currentScript 일 것이라고 생각했지만 이것이 보편적으로 지원되지는 않습니다. <script>요소는 확실하게 자신의 DOM 위치를 확인할 수 없습니다; 'this'에 대한 참조는 기본 창을 가리키며 도움이되지 않습니다.

나는 <img>구피에도 불구하고 요소 를 사용하기 위해 정착해야한다고 생각합니다 . 이것은 플러그를 사용할 수있는 DOM / javascript 프레임 워크의 구멍 일 수 있습니다.


MutationObserver를 사용하여 아래 샘플 코드를 효율적으로 추가하여 문제를 해결할 수 있습니다.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        #second{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: #a1a1a1;
        }
    </style>
</head>
<body>
<div id="first"></div>
<script>
    var callthis = function(element){
           element.setAttribute("tabIndex",0);
        element.focus();
        element.onkeydown = handler;
        function handler(){
                alert("called")
        }
    }


    var observer = new WebKitMutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for (var i = 0; i < mutation.addedNodes.length; i++)
            if(mutation.addedNodes[i].id === "second"){
                callthis(mutation.addedNodes[i]);
            }

        })
    });
    observer.observe(document.getElementById("first"), { childList: true });


    var ele = document.createElement('div');
    ele.id = "second"

    document.getElementById("first").appendChild(ele);

</script>

</body>
</html>

나는 이런 종류의 일을 위해 YUI3 라이브러리를 정말로 좋아합니다.

<div id="mydiv"> ... </div>

<script>
YUI().use('node-base', function(Y) {
  Y.on("available", someFunction, '#mydiv')
})

참조 : http://developer.yahoo.com/yui/3/event/#onavailable


속성 ( <body onload="myFn()"> ...)을 통해 또는 Javascript에서 이벤트를 바인딩 하여 body.onload 이벤트를 대신 사용하십시오 . 이것은 jQuery에서 매우 일반적입니다 .

$(document).ready(function() {
    doSomething($('#myDiv'));
});

나는 자바 스크립트와 jquery를 배우고 모든 대답을 겪고 있었고 div 요소를로드하기 위해 javascript 함수를 호출 할 때 동일한 문제에 직면했습니다. 나는 노력 $('<divid>').ready(function(){alert('test'})했고 그것은 나를 위해 일했다. jquery 선택기를 사용하는 방식으로 div 요소에서 onload 호출을 수행하는 좋은 방법입니다.

감사


모두 말했듯이 대신 DIV에서 onLoad 이벤트를 사용할 수 없지만 body 태그 앞에 사용할 수 있습니다.

그러나 바닥 글 파일이 하나 있고 여러 페이지에 포함시키는 경우. 원하는 div가 표시된 페이지에 있는지 먼저 확인하는 것이 좋습니다. 따라서 DIV가 포함되지 않은 페이지에서 코드가 실행되지 않아 더 빠르게로드하고 응용 프로그램의 시간을 절약 할 수 있습니다.

따라서 해당 DIV에 ID를 제공하고 다음을 수행해야합니다.

var myElem = document.getElementById('myElementId');
if (myElem !== null){ put your code here}

나는 같은 질문을했고 onload 또는 load를 사용하여 Div가 스크롤 스크립트를로드하도록하려고했습니다. 내가 찾은 문제는 Div가 열리기 전에 또는 작동하지 않고 항상 열리기 전에 항상 작동한다는 것이므로 실제로 작동하지는 않습니다.

그런 다음이 문제를 해결했습니다.

<body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);" 
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.


You could use an interval to check for it until it loads like this: https://codepen.io/pager/pen/MBgGGM

let checkonloadDoSomething = setInterval(() => {
  let onloadDoSomething = document.getElementById("onloadDoSomething");
  if (onloadDoSomething) {
    onloadDoSomething.innerHTML="Loaded"
    clearInterval(checkonloadDoSomething);
  } else {`enter code here`
    console.log("Waiting for onloadDoSomething to load");
  }
}, 100);

First to answer your question: No, you can't, not directly like you wanted to do so. May be a bit late to answer, but this is my solution, without jQuery, pure javascript. It was originally written to apply a resize function to textareas after DOM is loaded and on keyup.

Same way you could use it to do something with (all) divs or only one, if specified, like so:

document.addEventListener("DOMContentLoaded", function() {
    var divs = document.querySelectorAll('div'); // all divs
    var mydiv = document.getElementById('myDiv'); // only div#myDiv
    divs.forEach( div => {
        do_something_with_all_divs(div);
    });
    do_something_with_mydiv(mydiv);
});

If you really need to do something with a div, loaded after the DOM is loaded, e.g. after an ajax call, you could use a very helpful hack, which is easy to understand an you'll find it ...working-with-elements-before-the-dom-is-ready.... It says "before the DOM is ready" but it works brillant the same way, after an ajax insertion or js-appendChild-whatever of a div. Here's the code, with some tiny changes to my needs.

css

.loaded { // I use only class loaded instead of a nodename
    animation-name: nodeReady;
    animation-duration: 0.001s;
}

@keyframes nodeReady {  
    from { clip: rect(1px, auto, auto, auto); }
    to { clip: rect(0px, auto, auto, auto); }  
}

javascript

document.addEventListener("animationstart", function(event) {
    var e = event || window.event;
    if (e.animationName == "nodeReady") {
        e.target.classList.remove('loaded');
        do_something_else();
    }
}, false);

Since the onload event is only supported on a few elements, you have to use an alternate method.

You can use a MutationObserver for this:

const trackElement = element => {
  let present = false;
  const checkIfPresent = () => {
    if (document.body.contains(element)) {
      if (!present) {
        console.log('in DOM:', element);
      }
      present = true;
    } else if (present) {
      present = false;
      console.log('Not in DOM');
    }
  };

  const observer = new MutationObserver(checkIfPresent);
  observer.observe(document.body, { childList: true });
  checkIfPresent();

  return observer;
};

const element = document.querySelector('#element');
const add = () => document.body.appendChild(element);
const remove = () => element.remove();

trackElement(element);
<button onclick="add()">Add</button>
<button onclick="remove()">Remove</button>

<div id="element">Element</div>


When you load some html from server and insert it into DOM tree you can use DOMSubtreeModified however it is deprecated - so you can use MutationObserver or just detect new content inside loadElement function directly so you will don't need to wait for DOM events

var ignoreFirst=0;
var observer = (new MutationObserver((m, ob)=>
{
  if(ignoreFirst++>0) {
    console.log('Element add on', new Date());
  }
}
)).observe(content, {childList: true, subtree:true });


// simulate element loading
var tmp=1;
function loadElement(name) {  
  setTimeout(()=>{
    console.log(`Element ${name} loaded`)
    content.innerHTML += `<div>My name is ${name}</div>`; 
  },1500*tmp++)
}; 

loadElement('Michael');
loadElement('Madonna');
loadElement('Shakira');
<div id="content"><div>


Try this.

document.getElementById("div").onload = alert("This is a div.");
<div id="div">Hello World</div>

Try this one too. You need to remove . from oQuickReply.swap() to make the function working.

document.getElementById("div").onload = oQuickReplyswap();
function oQuickReplyswap() {
alert("Hello World");
}
<div id="div"></div>


You cannot add event onload on div, but you can add onkeydown and trigger onkeydown event on document load

$(function ()
{
  $(".ccsdvCotentPS").trigger("onkeydown");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<div  onkeydown="setCss( );"> </div>`

참고URL : https://stackoverflow.com/questions/4057236/how-to-add-onload-event-to-a-div-element

반응형