Я начинаю изучать некоторые базовые вещи JavaScript, и это было очень весело и круто :)

но у меня есть вопрос. Как изменить значение переменной в зависимости от значения?
Звучит странно, Надеюсь, это не так .

// added function cVal because it's the one thats gonna change
// the variable numbers in the 'error' variable.

function cVal(val) {
    error = val; 
}

// Main variables
var error = 0;
var span_open = "<span class='error-output'>";
var span_close = "</span>";
var span_open_r = "<span class='error-output warning'>";

// Error message variables
var err1 = "Unauthorized access to directory.";
var err2 = "Malformed server configuration.";
var err3 = "Unauthorized access to file.";
var err4 = "Malformed server database configuration.";
var err5 = "Unknown file type .xyz";
var err6 = "Unknown file type .xy";
var err7 = "Unknown file type .x";
var err8 = "Unknown file type .ztrs";
var err10 = "Cannot connect to MySQL database.";
var err11 = "Error connecting to MySQL database.";
var err12 = "Connection timeout on 'Connecting to MySQL Database'";

// File type variables

if (error == 0) {
    document.write(span_open, "No error detected.", span_close);
} else if (error == 1) {
    document.write(span_open, "Error: ", err1, span_close);
} else if (error == 2) {
    document.write(span_open, "Error: ", err2, span_close);
} else if (error == 3) {
    document.write(span_open, "Error: ", err3, span_close);
} else if (error == 4) {
    document.write(span_open, "Error: ", err4, span_close);
} else if (error == 5) {
    document.write(span_open, "Error: ", err5, span_close);
} else if (error == 6) {
    document.write(span_open, "Error: ", err6, span_close);
} else if (error == 7) {
    document.write(span_open, "Error: ", err7, span_close);
} else if (error == 8) {
    document.write(span_open, "Error: ", err8, span_close);
} else if (error == 9) {
    document.write(span_open, "Error: ", err9, span_close);
} else if (error == 10) {
    document.write(span_open, "Error: ", err10, span_close);
} else if (error == 11) {
    document.write(span_open, "Error: ", err11, span_close);
} else if (error == 12) {
    document.write(span_open, "Error: ", err12, span_close);
} else {
    document.write(span_open_r, "Error code ", error, " does not exist.", span_close);
}
span.error-output {
    background-color:#44d52b;
    color:#ffffff;
    font-family:Verdana;
    font-size:12px;
    padding:18px;
    box-sizing:padding-box;
    top:0px;
    left:0px;
    right:0px;
    margin:15px;
    border-radius:4px;
    box-shadow:7px 7px 15px #d7d7d7;
    opacity:0.5;
    transition:all .4s ease;
    position:absolute;
}

span.error-output:hover {
    opacity:1.0;
    box-shadow:9px 9px 20px #d7d7d7;
}

span.warning {
    background-color:#d20000;
}

.cVal_container {
    background-color:#e1e2e3;
    color:#000000;
    font-family:Verdana;
    font-size:12px;
    padding:18px;
    box-sizing:padding-box;
    top:64px;
    left:0px;
    right:0px;
    margin:15px;
    border-radius:4px;
    box-shadow:7px 7px 15px #d7d7d7;
    opacity:0.5;
    transition:all .4s ease;
    position:absolute;
}

.cVal_container:hover {
    opacity:1.0;
    box-shadow:9px 9px 20px #d7d7d7;
}

button {
    background-color:#aeb0b3;
    margin-top:4px;
    color:#262728;
    width:100%;
    font-family:Verdana;
    font-size:16px;
    border:0px;
    padding:4px;
    box-shadow:7px 7px 15px #d7d7d7;
    border-radius:4px;
    opacity:0.5;
    transition:all .4s ease;
}

button:hover {
    opacity:1.0;
    box-shadow:9px 9px 20px #d7d7d7;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <link rel="Stylesheet" type="text/css" href="style.css">
        <script src="main.js"></script>
    </head>
<body>
<div class="cVal_container">
    <button onclick="cVal(0)" type="button">Error Code 0 (Default)</button>
    <button onclick="cVal(1)" type="button">Error Code 1</button>
    <button onclick="cVal(2)" type="button">Error Code 2</button>
    <button onclick="cVal(3)" type="button">Error Code 3</button>
    <button onclick="cVal(4)" type="button">Error Code 4</button>
    <button onclick="cVal(5)" type="button">Error Code 5</button>
    <button onclick="cVal(6)" type="button">Error Code 6</button>
    <button onclick="cVal(7)" type="button">Error Code 7</button>
    <button onclick="cVal(8)" type="button">Error Code 8</button>
    <button onclick="cVal(9)" type="button">Error Code 9</button>
    <button onclick="cVal(10)" type="button">Error Code 10</button>
    <button onclick="cVal(11)" type="button">Error Code 11</button>
    <button onclick="cVal(12)" type="button">Error Code 12</button>
    <button onclick="cVal(13)" type="button">Error Code 13</button>
    <button onclick="cVal(14)" type="button">Error Code 14</button>
    <button onclick="cVal(15)" type="button">Error Code 15</button>
    <button onclick="cVal(16)" type="button">Error Code 16</button>
</div>
</body>
</html>



Я надеюсь, что некоторые из вас поймут, что я хочу здесь делать.
Поэтому, чтобы объяснить дальше ...

Если onclick="cVal(2)" назначен на КНОПКУ, измените переменную error на значение 2, Но это не работает .

< br /> Так что же я здесь не так делаю?
Пожалуйста, включите код только для javascript, jQuery и другие в данный момент мне не подходят.


Спасибо заранее :)

0
Soricy Infinitive 28 Май 2017 в 00:30

2 ответа

Лучший ответ

Добро пожаловать в JS, надеюсь, это будет отличное путешествие :)

Помимо ясности кода, изменение значения «error» фактически работает в вашем коде. Но если вы надеетесь получить различную ошибку после каждого клика, этого не происходит, поскольку JS по умолчанию запускается один раз, во время (или после) загрузки страницы. Итак, что вам нужно сделать, это заключить некоторую часть кода в функцию, которая будет вызываться после каждого щелчка (и использовать что-то другое, чем document.write).

// added function cVal because it's the one thats gonna change
// the variable numbers in the 'error' variable.

function cVal(val) {
    error = val; 
    updateError()
}

// Main variables
var error = 0;
var span_open = "<span class='error-output'>";
var span_close = "</span>";
var span_open_r = "<span class='error-output warning'>";

// Error message variables
var err1 = "Unauthorized access to directory.";
var err2 = "Malformed server configuration.";
var err3 = "Unauthorized access to file.";
var err4 = "Malformed server database configuration.";
var err5 = "Unknown file type .xyz";
var err6 = "Unknown file type .xy";
var err7 = "Unknown file type .x";
var err8 = "Unknown file type .ztrs";
var err10 = "Cannot connect to MySQL database.";
var err11 = "Error connecting to MySQL database.";
var err12 = "Connection timeout on 'Connecting to MySQL Database'";

var ec = document.getElementById('error_container');
// File type variables
function updateError(){
if (error == 0) {
    ec.innerHTML = span_open+ "No error detected."+ span_close
} else if (error == 1) {
    ec.innerHTML = span_open+ "Error: "+ err1, span_close
} else if (error == 2) {
    ec.innerHTML = span_open+ "Error: "+ err2, span_close
} else if (error == 3) {
   ec.innerHTML = span_open+ "Error: "+ err3, span_close
} else if (error == 4) {
   ec.innerHTML = span_open+ "Error: "+ err4, span_close
} else if (error == 5) {
   ec.innerHTML = span_open+ "Error: "+ err5, span_close
} else if (error == 6) {
   ec.innerHTML = span_open+ "Error: "+ err6, span_close
} else if (error == 7) {
   ec.innerHTML = span_open+ "Error: "+ err7, span_close
} else if (error == 8) {
   ec.innerHTML = span_open+ "Error: "+ err8, span_close
} else if (error == 9) {
   ec.innerHTML = span_open+ "Error: "+ err9, span_close
} else if (error == 10) {
   ec.innerHTML = span_open+ "Error: "+ err10, span_close
} else if (error == 11) {
  ec.innerHTML = span_open+ "Error: "+ err11, span_close
} else if (error == 12) {
   ec.innerHTML = span_open+ "Error: "+ err12, span_close
} else {
   ec.innerHTML = span_open_r +"Error code "+error+ " does not exist."+span_close
}
}
updateError()
span.error-output {
    background-color:#44d52b;
    color:#ffffff;
    font-family:Verdana;
    font-size:12px;
    padding:18px;
    box-sizing:padding-box;
    top:0px;
    left:0px;
    right:0px;
    margin:15px;
    border-radius:4px;
    box-shadow:7px 7px 15px #d7d7d7;
    opacity:0.5;
    transition:all .4s ease;
    position:absolute;
}

span.error-output:hover {
    opacity:1.0;
    box-shadow:9px 9px 20px #d7d7d7;
}

span.warning {
    background-color:#d20000;
}

.cVal_container {
    background-color:#e1e2e3;
    color:#000000;
    font-family:Verdana;
    font-size:12px;
    padding:18px;
    box-sizing:padding-box;
    top:64px;
    left:0px;
    right:0px;
    margin:15px;
    border-radius:4px;
    box-shadow:7px 7px 15px #d7d7d7;
    opacity:0.5;
    transition:all .4s ease;
    position:absolute;
}

.cVal_container:hover {
    opacity:1.0;
    box-shadow:9px 9px 20px #d7d7d7;
}

button {
    background-color:#aeb0b3;
    margin-top:4px;
    color:#262728;
    width:100%;
    font-family:Verdana;
    font-size:16px;
    border:0px;
    padding:4px;
    box-shadow:7px 7px 15px #d7d7d7;
    border-radius:4px;
    opacity:0.5;
    transition:all .4s ease;
}

button:hover {
    opacity:1.0;
    box-shadow:9px 9px 20px #d7d7d7;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <link rel="Stylesheet" type="text/css" href="style.css">
        <script src="main.js"></script>
    </head>
<body>
<div id="error_container"></div>
<div class="cVal_container">
    <button onclick="cVal(0)" type="button">Error Code 0 (Default)</button>
    <button onclick="cVal(1)" type="button">Error Code 1</button>
    <button onclick="cVal(2)" type="button">Error Code 2</button>
    <button onclick="cVal(3)" type="button">Error Code 3</button>
    <button onclick="cVal(4)" type="button">Error Code 4</button>
    <button onclick="cVal(5)" type="button">Error Code 5</button>
    <button onclick="cVal(6)" type="button">Error Code 6</button>
    <button onclick="cVal(7)" type="button">Error Code 7</button>
    <button onclick="cVal(8)" type="button">Error Code 8</button>
    <button onclick="cVal(9)" type="button">Error Code 9</button>
    <button onclick="cVal(10)" type="button">Error Code 10</button>
    <button onclick="cVal(11)" type="button">Error Code 11</button>
    <button onclick="cVal(12)" type="button">Error Code 12</button>
    <button onclick="cVal(13)" type="button">Error Code 13</button>
    <button onclick="cVal(14)" type="button">Error Code 14</button>
    <button onclick="cVal(15)" type="button">Error Code 15</button>
    <button onclick="cVal(16)" type="button">Error Code 16</button>
    
</div>
</body>
</html>
1
Michał Sałaciński 27 Май 2017 в 22:07

Немного изменил ваш код. Последний известный код ошибки можно получить, вызвав displayError.lastError Чтобы обновить сообщение об ошибке, позвоните displayError(1) // see the errors object for more detail

РЕДАКТИРОВАТЬ: добавил комментарии к .js

/**
 * Error object
 * @type {Object}
 */
var errors = {
  1: "Unauthorized access to directory.",
  2: "Malformed server configuration.",
  3: "Unauthorized access to file.",
  4: "Malformed server database configuration.",
  5: "Unknown file type .xyz",
  6: "Unknown file type .xy",
  7: "Unknown file type .x",
  8: "Unknown file type .ztrs",
  10: "Cannot connect to MySQL database.",
  11: "Error connecting to MySQL database.",
  12: "Connection timeout on 'Connecting to MySQL Database'",
};

/**
 * Display error in DIV with ID 'error-container', based on error code
 * @see errors Defined error codes
 * @param {number|string} errorCode
 */
function displayError(errorCode) {
  var errorContainer = document.getElementById('error-container');
  if (!errorContainer) {
    throw new Error('Unable to display error. Element with id "error-container" does not exist in the DOM.');
  }
  // Reset the class name for the error container
  errorContainer.className = 'error-output';
  // Store the last known error code as a "static property"
  displayError.lastError = errorCode;
  // Check if errorCode is a property in the errors object
  // Also check that we dont try to access inherited props
  if (errorCode in errors && errors.hasOwnProperty(errorCode)) {
    // Set the content of the error container
    errorContainer.innerHTML = 'Error: ' + errors[errorCode];
  } else {
    // Set the content of the error container
    errorContainer.innerHTML = "Error code " + errorCode + " does not exist.";
    // Append the warning class name
    errorContainer.className += ' warning';
  }
}
// Set an initial value of lastError
displayError.lastError = 0;
span.error-output {
  background-color: #44d52b;
  color: #ffffff;
  font-family: Verdana;
  font-size: 12px;
  padding: 18px;
  box-sizing: padding-box;
  top: 0px;
  left: 0px;
  right: 0px;
  margin: 15px;
  border-radius: 4px;
  box-shadow: 7px 7px 15px #d7d7d7;
  opacity: 0.5;
  transition: all .4s ease;
  position: absolute;
}

span.error-output:hover {
  opacity: 1.0;
  box-shadow: 9px 9px 20px #d7d7d7;
}

span.warning {
  background-color: #d20000;
}

.cVal_container {
  background-color: #e1e2e3;
  color: #000000;
  font-family: Verdana;
  font-size: 12px;
  padding: 18px;
  box-sizing: padding-box;
  top: 64px;
  left: 0px;
  right: 0px;
  margin: 15px;
  border-radius: 4px;
  box-shadow: 7px 7px 15px #d7d7d7;
  opacity: 0.5;
  transition: all .4s ease;
  position: absolute;
}

.cVal_container:hover {
  opacity: 1.0;
  box-shadow: 9px 9px 20px #d7d7d7;
}

button {
  background-color: #aeb0b3;
  margin-top: 4px;
  color: #262728;
  width: 100%;
  font-family: Verdana;
  font-size: 16px;
  border: 0px;
  padding: 4px;
  box-shadow: 7px 7px 15px #d7d7d7;
  border-radius: 4px;
  opacity: 0.5;
  transition: all .4s ease;
}

button:hover {
  opacity: 1.0;
  box-shadow: 9px 9px 20px #d7d7d7;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width">
  <link rel="Stylesheet" type="text/css" href="style.css">
  <script src="main.js"></script>
</head>

<body>
  <span id="error-container" class="error-output">Press a button to test</span>
  <div class="cVal_container">
    <button onclick="displayError(0)" type="button">Error Code 0 (Default)</button>
    <button onclick="displayError(1)" type="button">Error Code 1</button>
    <button onclick="displayError(2)" type="button">Error Code 2</button>
    <button onclick="displayError(3)" type="button">Error Code 3</button>
    <button onclick="displayError(4)" type="button">Error Code 4</button>
    <button onclick="displayError(5)" type="button">Error Code 5</button>
    <button onclick="displayError(6)" type="button">Error Code 6</button>
    <button onclick="displayError(7)" type="button">Error Code 7</button>
    <button onclick="displayError(8)" type="button">Error Code 8</button>
    <button onclick="displayError(9)" type="button">Error Code 9</button>
    <button onclick="displayError(10)" type="button">Error Code 10</button>
    <button onclick="displayError(11)" type="button">Error Code 11</button>
    <button onclick="displayError(12)" type="button">Error Code 12</button>
    <button onclick="displayError(13)" type="button">Error Code 13</button>
    <button onclick="displayError(14)" type="button">Error Code 14</button>
    <button onclick="displayError(15)" type="button">Error Code 15</button>
    <button onclick="displayError(16)" type="button">Error Code 16</button>
  </div>
</body>

</html>
0
Thomas Wikman 27 Май 2017 в 22:19