查找并删除<脚本>SRC属性为空的元素

Find and remove <script> element with empty src attribute

本文关键字:属性 元素 SRC 脚本 删除 查找      更新时间:2023-09-26

Facebook Plugin for wordpress有一个问题,它添加一个脚本元素的DOM与空src属性。

http://wordpress.org/support/topic/w3c-validation-error-caused-my-empty-src-tag-generated-by-plugin?replies=3

<script type='text/javascript' src=''></script>

上面的链接建议编辑核心WP文件。问题是,是否有一种方法来查找和删除使用jQuery?

如下所示,无法定位空src/script元素

$('footer script').each(function(){ 
        if($(this).attr('src') == 'undefined' && $(this).length < 1){
            $(this).remove();  
        } 
     })

编辑:既然问这个问题,我已经意识到我需要删除脚本元素使用PHP,为了页面验证。

你就快成功了:

$('footer script').each(function(){ 
    if(!$(this).attr("src")){
        $(this).remove();  
    } 
 });

这将删除所有带有空src的脚本标签。但是,这并不能防止验证失败。

我没有测试s bastien的解决方案。我只需要找到带有空src的脚本标签,并对它们做一些不同的事情(将data-src复制到src以获得隐私保护,如果获得同意,src将被设置),但删除也有效。

$('footer script[src=""]').each(function () {
    $(this).remove();
});

FWIW:通过data-src设置src如下:

$(this).find('script[src=""]').each(function () {
    var src = $(this).data('src');
    $(this).attr('src', src).show();
});

也可以用iframe代替script