如何使用Jquery替换整个HTML页面中的占位符?

3

我有一个 HTML 演示页面,其中包含一个占位符 "||client||"。它在整个页面中都有使用,例如:

<img src="images/||_client_||/img1.jpg" />

或者

<title>||_client_|| Demo</title>

等等。

我希望在页面加载时全局替换占位符为相应的客户端ID。该页面仅用于演示目的,因此不想设置任何服务器端内容。

我绑定到这个:

 $('div:jqmData(role="page")').on('pagebeforecreate', function() {  
  // replace ||_client_|| with some ID      
  });

问题:
是否有一种Jquery方法可以遍历DOM并查找所有占位符的实例并替换它们,还是我必须逐个手动查找所有img标签,检查src中的子字符串并替换此子字符串?一定有更好的方法吧?

谢谢帮助!


这样做服务器端处理不是更好吗?还是你使用静态HTML? - m90
这是一个静态的模型。只有占位符会改变。 - frequent
不要认为有一个一站式的解决方案。您需要遍历每个可能的设置(属性、html等),并使用类似.replace()的东西来处理它们。 - m90
5个回答

3
你可以滚动浏览页面上的每个<img />对象,然后进行搜索/替换。
$('div:jqmData(role="page")').on('pagebeforecreate', function() { 

    $('img').each(function(){
        var newVal = $(this).attr('src').replace('||_client_||', theClientId);
        $(this).attr('src', newVal);
    });

});

不过,我建议您使用精确的选择器来遍历特定 div 中的图像$('#theDiv img')或某个类别的图像$('img.placeholder'),而不是使用$('img')。其中,类别选择器可能是最好的选择。您只需要在要遍历的每个图像中添加class="placeholder"即可。


我喜欢捆绑的想法...这对于<img>和<link>标签都应该适用,不是吗? - frequent
这将适用于任何具有“src”属性的实体类型。 - Dutchie432

2

你为什么需要jQuery?

document.body.innerHTML = document.body.innerHTML.replace(/\|\|_client_\|\|/g, 'your text here');

整个页面:

var html = document.getElementsByTagName('html')[0];
html.innerHTML = html.innerHTML.replace(...);

作为一种警告,确保在页面准备好之后(以便主体具有所有元素)执行此操作,并在绑定事件到任何元素之前执行。


不一定非得用jQuery,只要效果好看就行。有没有办法包含文档头(我还需要更改一些链接元素)? - frequent
document.getElementsByTagName('html')[0].innerHTML,或者 document.head.innerHTMLdocument.body.innerHTML - zzzzBov

1

实际上你可以这样做:

//getting the html dom as string
var myStr = $("body").html();
//use reguler expression to replace your placeholder
myStr = myStr.replace(/\|\|\_client\_\|\|/gi,"Fareed");
//return it back to the dom
$("body").html(myStr);

注:/ gi用于全局和不区分大小写


1
这是一个示例,将在整个文档中替换所有的 '||client||' 为 "replace_string"。
<html>
    <head>
        <title>||_client_|| Demo</title>
    </head>
    <body>
        <h1>||_client_||</h1>
        <img src="images/||_client_||/img1.jpg" />       
    </body>
    <script type="text/javascript">
        document.documentElement.innerHTML = document.documentElement.innerHTML.split('||_client_||').join('replace_string');
    </script>
</html>

0
你可以使用 .html() 函数将整个页面转换为 html,然后替换占位符并使用 .html() 设置结果。这可能不是非常高效,但对你可能有用。
// Suppose we have a div with a test class: <div class="test">{PLACEHOLDER} title</div>
var div = $('.div')
var src = $(div).html()
src = src.replace('{PLACEHOLDER}', 'Test')
div.html(src)

// Your div now contains: <div class="test">Test title</div>

祝你好运!


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