gpt4 book ai didi

javascript - 如何从脚本内获取 document.currentscript 并指向parentNode

转载 作者:行者123 更新时间:2023-12-03 00:53:23 25 4
gpt4 key购买 nike

当用户滚动页面时,我将附加一个 div 标签,并在同一 div 中附加一个 js 标签。

现在,我用“js_div_1”、“js_div_2”、“js_div_3”等指向父标记,并附加一些内容。

HTML 形式:

<div id="divider" class="long">
<!-- Firt iteration - when document ready-->
<div id="js_div_1" >
<script async="" id="js_file_1" type="text/javascript" src="sample.js"></script>
</div>

</div>

这是我的代码:

$(document).ready(function(){
var divCounter = 0;
if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
// you're at the bottom of the page
console.log("Reached bottom and load more content here");
divCounter++;


var slotDiv = document.createElement('div');
slotDiv.id = 'js_div_'+divCounter; // Id must be the same as slotName
$('#divider').append(slotDiv);

var adScript = document.createElement('script');
adScript.async = true;
adScript.id = "js_file_"+divCounter;
adScript.type = 'text/javascript';
adScript.src = "sample.js";
$('#js_div_'+divCounter).append(adScript);
}
});

sample.js文件内容内:

console.log(document.currentScript);    
var parentTag = document.currentScript;
parentTag.parentNode.removeChild(parentTag );
parentTag.parentNode.appendChild('Success');

实际输出:(console.log)

<script>
console.log(document.currentScript);
var parentTag = document.currentScript;
parentTag.parentNode.removeChild(parentTag );
parentTag.parentNode.appendChild('Success');
</script>

预期输出:(需要指向parentNode div'js_div_1'并附加响应)

 <div id="divider" class="long">
<!-- 1st iteration - when document ready-->
<div id="js_div_1" >
Success
</div>

<!-- 2nd iteration - when document ready-->
<div id="js_div_1" >
Success
</div>
<!-- 3nd iteration -->
etc...
</div>

最佳答案

为了能够编写更快的 JavaScript 代码,您必须稍微更改一下 Html:

HTML 代码:

<div id="divider" class="long">
<!-- Firt iteration - when document ready-->
<div id="js_div_1" class="js-div-container" data-iteration="1" >
<script async="" id="js_file_1" class="js-link" type="text/javascript" src="sample.js"></script>
</div>

</div>

Javascript代码:

jQuery(document).ready(function($){
$(window).scroll(function(){
var scrollHeight = $(document).height();
var scrollPosition = $(this).height() + $(this).scrollTop();

if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
// when scroll to bottom of the page
var el = $('.js-div-container:last-child');
var iteration = parseInt(el.attr("data-iteration")) + 1;

el.clone().attr({'id': 'js_div_' + iteration, 'data-iteration': iteration}).appendTo('#divider');

el.find('.js-link').attr('id', 'js_file_' + iteration);
}
});
});

这些代码将输出预期的结果。但我不明白为什么这个脚本sample.js必须被加载多次?

关于javascript - 如何从脚本内获取 document.currentscript 并指向parentNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com