简体   繁体   English

加载div后调用js函数

[英]Call js function after div is loaded

I have a div element which is loaded after a click on a radio button.我有一个 div 元素,它在单击单选按钮后加载。

Need to hide a part of the div after it is loaded.加载后需要隐藏部分div。

$(function($) {
  $('.div_element').on('load', function() {
    $('.textbox').hide();
  });
});

The above code doesn't work.上面的代码不起作用。 I need to trigger a function after the div is shown on the page.我需要在页面上显示 div 后触发一个函数。

Although it may not be good solution but you can check in an interval if the div exist, if it is then you can do further:虽然这可能不是一个好的解决方案,但是如果 div 存在,您可以检查一个时间间隔,如果存在,那么您可以进一步执行:

$(() => {
  const checkDiv = setInterval(() => {
    if($('.div_element').length > 0) {    // it's better to use id instead of the class as selector
      clearInterval(checkDiv);
      // more action here
    } 
  }, 100); // check after 100ms every time
});

Here is how I would go about it.这是我将如何去做。 This is using vanilla JavaScript but it can easily be adapted to use jQuery.这是使用 vanilla JavaScript,但它可以很容易地适应使用 jQuery。

The idea is to use Mutation Observers .这个想法是使用Mutation Observers I hope it helps.我希望它有帮助。

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>DOM MUTATION OBSERVERS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
    <form name="radios">
        <input type="radio" name="gender" value="male" id="maleRadio" checked> Male
        <br>
        <input type="radio" name="gender" value="female" id="femaleRadio"> Female
        <br>
        <input type="radio" name="gender" value="other" id="otherRadio"> Other
    </form>

    <!-- This div will be displayed when the radio button whose value is female is clicked. -->
    <div id="femaleDiv" style="display: none">
        <p>The textbox should be below...</p>
        <input type="text" id="textToHide">
    </div>

    <script>
        // After the document loads...
        document.onload = function () {
            // Attach an onclick listener to the radio buttons.
            var radios = document.forms["radios"].elements["gender"];
            for (var i = 0, max = radios.length; i < max; i++) {
                radios[i].onclick = function (event) {
                    var radio = event.target || event.srcElement;
                    console.log(radio.name);
                    if (radio.value === "female") {
                        document.getElementById("female").style.display = "block"
                    }
                }
            }

            // Get the div whose change in attributes we are interested in.
            var targetNode = document.getElementById("femaleDiv");

            // Set the mutation observer to only listen to attribute mutations
            var config = { attributes: true };

            // This will be called when a mutation has been observed
            var callback = function(mutationsList) {
                for (var mutation of mutationsList) {
                    if (mutation.type == "attributes") {
                        console.log(mutation);
                        console.log('The ' + mutation.attributeName + ' attribute was modified.');
                        if (targetNode.style.display == "block") {
                            document.getElementById("textToHide").style.display = "none";
                        }
                    }
                }
            };

            // Create the observer
            var observer = new MutationObserver(callback);

            // Start observing
            observer.observe(targetNode, config);

            // Uncomment this to stop observing at at the right place.
            // observer.disconnect();
        } ();
    </script>
</body>

</html>

Check Div is initialized检查 Div 是否已初始化

 $(document).ready(function(){ var textBox="<input type='text' class='textbox'>"; $(".textboxContainer").html(textBox); var divNew="<div class='div_element'>DIV to Load</div>"; $(".domNewDiv").html(divNew); var divNew1="<div class='div_element'>DIV to Load 2</div>"; $(".domNewDiv").html(divNew1); }); $(".div_element").init( function(){ $('.textboxContainer').find('.textbox').hide(); })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='textboxContainer'></div> <div class='domNewDiv'> </div>

As far as my understanding, you need to perform an action on clicking of a radio button.据我了解,您需要在单击单选按钮时执行操作。 This is where your code should start.这是您的代码应该开始的地方。

$("input[name='YOUR_BUTOTN_NAME_GOES_HERE']").click(function(){
//I suggest to use a same class for both the radio buttons you want to click as this will effect for all the radio buttons
    console.log('You clicked radio!');
    var checkDivLength = setInterval(function(){
   if($('.div_element').length > 0) {

      //Hide your element
      $('.textbox').hide();
      clearInterval(checkDivLength);
   } 
   }, 100);
});

Please note that in this line "$("input[name='YOUR_BUTOTN_NAME_GOES_HERE']").click(function(){" you need to give the name attribute which you have used in your code. Eg <input type="radio" name="sample" value="test"> then your code should be "$("input[name='sample']").click(function(){"请注意,在这一行"$("input[name='YOUR_BUTOTN_NAME_GOES_HERE']").click(function(){"你需要给出你在代码中使用的 name 属性。例如<input type="radio" name="sample" value="test">那么你的代码应该是"$("input[name='sample']").click(function(){"

Thanks :)谢谢 :)

You can invoke it using " () ", when the event calls:当事件调用时,您可以使用“ () ”调用它:

$(function($) {
  $('.div_element').on('load', function() {
    $('.textbox').hide();
  }());
});

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

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