简体   繁体   English

HTML源中的JavaScript检查

[英]JavaScript Checking in HTML source

So I have a variable in my script var mystring = "123" and my web page look like this 所以我在脚本中有一个变量var mystring = "123" ,我的网页看起来像这样

<body>  
<div id="footer">   
123  
</div> </body>

I need a script that checks if the variable is the same as the footer content and if is not, replace it. 我需要一个脚本来检查变量是否与页脚内容相同,如果不相同,请替换它。

Just like this : 像这样 :

a="123";  
if a == html.content.from.footer then  
   do nothing;   
else   
   replace html.content.from.footer with a;

There's no need to check if the values are equal, because if you replace a value with an equal value then there's no change anyway. 无需检查值是否相等,因为如果将值替换为相等的值,则始终没有变化。 So all you really need to do is replace the value. 因此,您真正需要做的就是替换值。 Something like this: 像这样:

document.getElementById('footer').innerHTML = mystring;

Using jQuery, this is simple: 使用jQuery,这很简单:

if($("#footer").html() !== mystring) {
    $("#footer").html(mystring)
}

Without jQuery: 没有jQuery:

if(document.getElementById('footer').innerHTML !== mystring) {
    document.getElementById('footer').innerHTML = mystring;
}

Here, 这里,

<script>
 var mystring = "123";
 var footer = document.getElementById("footer");
 if(footer.innerHTML != mystring){
   footer.innderHTML = mystring;
 }
</script>

PS. PS。 I agree with David that you don't need to check if you know the string you want in the footer anyway. 我同意David的观点,无论如何您都不需要检查是否知道要在页脚中找到的字符串。 Just adding the script with the if block because you asked it that way. 只需添加带有if块的脚本,因为您是这样询问的。 Hope this helps. 希望这可以帮助。

var myVar = '1234';
var element = document.getElementById('footer');

if(myVar != element.innerHTML) {
    element.innerHTML = myVar;
}

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

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