在 div 加载完成后调用 js 函数

5

我有一个div元素,它是在单选按钮点击后加载的。

需要在加载后隐藏该div的一部分。

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

上述代码无法生效。我需要在div显示在页面上后触发一个函数。

1
一个 <div> 不会“加载”。你想在 <div> 出现在 DOM 中时立即调用一个函数吗?搜索变异观察器。如果 <div> 不在 DOM 中,那么你无法将事件监听器绑定到它上面。 - Sebastian Simon
你能添加一段可工作的代码片段吗?这样调试起来会更容易和更快速。 - Vikasdeep Singh
@Xufox 是的,在单选按钮被点击后,div会显示在页面上。然后我需要隐藏加载的div中的一个文本框。 - phpblogger
@phpblogger,你的隐藏代码是什么? - Kiran Shahi
@KiranShahi 已更新问题。重复链接的第一个参数是“一些url”,我没有可以在那个位置使用的任何内容,是否还有其他可能性? - phpblogger
在创建 div 的同时隐藏其中的一部分。 - Terry Wei
5个回答

2
这是我的做法。使用的是原生JavaScript,但可以轻松地改为使用jQuery。
思路是使用变异观察器。希望能对你有所帮助。
<!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>

2

虽然这可能不是一个好的解决方案,但你可以在一定时间间隔内检查 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
});

这个有效。谢谢。但是如预期的那样,加载主div需要更多时间 :-(。很遗憾,该元素没有onload事件,可以根据div的可见性进行操作。 - phpblogger

0
据我所知,您需要在单选按钮被点击时执行操作。这是您的代码应该开始的地方。
$("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);
});

请注意,在此行中"$("input[name='YOUR_BUTOTN_NAME_GOES_HERE']").click(function(){",您需要提供您在代码中使用的名称属性。例如<input type="radio" name="sample" value="test">,那么您的代码应该是"$("input[name='sample']").click(function(){"

谢谢 :)


0

检查 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>


已经尝试过了 - 在 div 加载后它不起作用。只是在页面加载时检查 div 是否存在。 - phpblogger

-1

当事件被调用时,您可以使用“()”来调用它:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接