如何在javascript中替换字符串变量的值?

时间:2015-07-05 02:26:21

标签: javascript

按下按钮时,我需要一种在两种模式之间切换的方法。

我的问题的类比:

按下按钮"打开和关闭"警报说" On"或"关"

如何在值之间交替使用字符串:" On"和"关"通过每次按下检查当前值的按钮更新字符串的值并替换?

界面

<button onclick="changeState();">Push me</button>

脚本

<script> 

var string = "up"; 

function changeState(){

  if(string=="up"){
  // switching to off
    var string = "down"; // I'm just redeclaring or declaring a new variable right? scope? 
    alert(Off);
    }else{
    // switching to on assuming current state is off
      var string = "up";
      // new state
      alert('on');
    }

  }

}
</script>

2 个答案:

答案 0 :(得分:2)

你在这里。我删除了&#39; var&#39;让它全球化,也删除ssPagesPDF = new RLPDFRecordList(null); ssErrors = ""; //Document document = null; PdfImportedPage importedPage = null; try { int TotalPages = 0; MssCountPagesPDF(ssPDF.ssSTPDF.ssBinaryData, out TotalPages, out ssErrors); if (TotalPages == 0) throw new Exception("The PDF don't have any page!"); for (int i = 1; i <= TotalPages; i++) { PdfReader reader = new PdfReader(ssPDF.ssSTPDF.ssBinaryData, System.Text.ASCIIEncoding.ASCII.GetBytes(ssPDF.ssSTPDF.ssPDFPassword)); // Capture the correct size and orientation for the page: using (MemoryStream target = new MemoryStream()) { using (Document document = new Document(reader.GetPageSizeWithRotation(i))) { using (PdfCopy pdfCopyProvider = new PdfCopy(document, target)) { document.Open(); // Extract the desired page number: importedPage = pdfCopyProvider.GetImportedPage(reader, i); pdfCopyProvider.AddPage(importedPage); //close the document document.Close(); reader.Close(); //Append PDF to the RecordList RCPDFRecord rcPDF = new RCPDFRecord(); rcPDF.ssSTPDF.ssBinaryData = target.ToArray(); ssPagesPDF.Append(rcPDF); } } } } } catch (Exception exception) { ssErrors = exception.ToString(); throw new Exception("There has an unexpected exception" + " occured during the pdf creation process.", exception); } 备用:

&#13;
&#13;
}
&#13;
var string = "up";

function changeState() {
  if (string == "up") {
    // switching to off
    string = "down"; // I'm just redeclaring or declaring a new variable right? scope? 
    alert("off");
  } else {
    // switching to on assuming current state is off
    string = "up";
    // new state
    alert('on');
  }
}
&#13;
&#13;
&#13;

希望得到这个帮助。

答案 1 :(得分:1)

var string = "up";

function changeState() {
  
  string = string =="up" ? "down" : "up";  

}