开发者

comparing innerHTML value with a string variable in javascript

开发者 https://www.devze.com 2023-01-29 07:02 出处:网络
function Open() { var cc = document.getElementById(\'FName\'); if (\'Newfile.rtf\' == cc.innerHTML) { alert(\"New File\");
function Open() {

  var cc = document.getElementById('FName');

  if ('Newfile.rtf' == cc.innerHTML) 
  {
     alert("New File");
  } //close If NewFile.rtf
  else {
     alert("Not new file");
  }
}//close Open()   

Here I have string "NewFile.rtf" in a element with id="FName" on the page. When the FName contains "Newfile.rtf" in it it stills goes to the else part of the function instead of going to if part. I tried different ways to write the compare statement in the if condition, no luck . Appreciate the help if anyo开发者_如何学JAVAne can help figure out this.

Thank you.


The simplest explanation is that your cc.innerHTML call is not returning what you think it is returning. Why don't you console.log or debug.

add something like

var innerhtml = cc.innerHTML;
console.log("innerHTML = " + innerhtml) // wont work in IE.

before the if statement.


Try using regular expressions to find your filename, also check if the text you are searching is not into another DOM element, elimate left and right spaces, you should use Google Chrome for debuging the Javascript code:

var html = document.getElementById('FName').innerHTML; 
if( html.search("Newfile.rtf") != -1) { /*found*/ }
else { /*not found*/ }


but what's the type of this element? if it's about an input text type .. you can't use innerHTML but you'll use value then.


Use innerText to get that

function Open() {

    var cc = document.getElementById('FName');

    if ('Newfile.rtf' == cc.innerText)
    {
        alert("New File");
    } //close If NewFile.rtf
    else {
        //enter code here
        alert("Not new file");
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消