javascript - 使用 if 语句和 jquery 更改 html 内容

标签 javascript jquery if-statement

我正在尝试根据选择菜单的值显示某些句子和图像。

如果用户选择他的平台是“Android”,那么他将看到一条特定消息。如果他选择他的平台是“iOS”,那么他会看到另一个。

我想使用变量“isAndroid”来实现此目的,如果为 true,它将显示 Android 消息和 android 图标,如果为 false,它将显示 iOS 消息和 iOS 图标。

然后我实现了 jquery 方法“change()”,以便每当选择器值在“Android”和“iOS”之间更改时就能够切换和更改内容。我已经设法以不同且更复杂的方式实现我的目标,但我想用这个 bool 值来实现它,以便稍后在更多东西上使用它,如果“isAndroid”为真,它会做很多其他事情,但我为了简单起见,此处显示基本内容。

这是我实际的 HTML 和 Javascript 代码:

function platformAndroid() {  //function with the content of Android. it should run if "esAndroid" is true
			$("#iconoDispositivo").attr("src","http://i.imgur.com/ksYWdrF.png");
			$("#chosenPlatform").html("Your chosen platform was android");
		}

		function platformIos(){   //function with the content of iOS. it should run if "esAndroid" is false
			$("#iconoDispositivo").attr("src","http://i.imgur.com/YPqQsib.png");
			$("#chosenPlatform").html("Your chosen platform was iOS")
		}

		var isAndroid = true;                    

		function dispositivoStart(){                    // this functions displays the correct stuff when user refresh the page                                                                                                                                  
			if($('#dispositivo').val() === "Android"){  //if my select input value is android, then "esAndroid" is true
				isAndroid;
			} else {
			 	isAndroid = false;                      // otherwise it is false
			}

			$('#dispositivo')on.("change",function(){        //here i wrote this piece of code to switch "esAndroid" to true or false when they select different values on the selector input
				if($(this).val() === "Android"){
					isAndroid;
				} else {
				 	isAndroid = false;
				}
			})


			if(isAndroid){            // here is the piece of code that displays the content. if esAndroid is true, then the function that displays "Android" content runs.
				platformAndroid()  
			} else {
				platformIos()      //if "esAndroid" is false, then the function that displays  "iOS" content runs
			}
			
		}

		dispositivoStart();
    
#chosenPlatform {
font-size: 20px;
color: green;
}
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>
		Platform choose
	</title>
</head>
<body>
	<h2>Platform</h2>
	<div class="field">
	    <label for="dispositivo">Choose your platform</label><br>
	    <select id="dispositivo">
	        <option>Android</option>
	        <option>iOS</option>
	    </select>
	</div>
	<div class="field">
	    <p id="chosenPlatform">Your chosen platform was Android</p>	<img src="http://i.imgur.com/ksYWdrF.png" width="32" alt="androidIcon" id="iconoDispositivo"> 
	</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js"></script>
</body>
</html>

我不明白为什么在代码片段中我无法正确调用jquery,在我自己的文件中我使用cdns,但这就是我试图运行的代码。

在当前代码中,“isAndroid”的 bool 值更改为 false,但不会显示“isAndroid”为 false 时应显示的内容(iOS 内容)。当选择输入值再次切换到“Android”时,它也不会切换回 true。

正如我一开始所说,如果我使用,我就可以实现我的目标

#dispositivo.val() === "Android" 

但我认为执行“isAndroid”= true/false 更简单,因为稍后我必须继续使用该 bool 值来根据该选择器值显示某些内容。

我希望我说得足够清楚,这是我在 Stackoverflow 上写的第二个问题,提前致谢。

最佳答案

在解决您的主要问题之前,我们应该先解决您的 HTML。通过 a validator 运行 HTML (不是 W3C,它已经过时了)。该演示提供了一个将 HTML 内容插入 <section> 的工作示例。以及在 <output> 中设置的值表单控件,由用户选择 <select> 确定.

方法、属性和流程

jQuery

.on() Event Delegation

.html() , .text() , & .val()

JavaScript

ES6 Template Literals

switch()

详细信息在演示中评论

演示

/* NOTE: ES6 Template Literals are being used instead of
|| String Literals:

[Example: String Literal >>> 
   var SL = "This is a String, this is a " + variable\ 
   + " concatenated";
   
[Example: Template Literal >>>  
   var TL = `This is a String, this is a ${variable}
   interpolated`;
*/
   
/* Register change event on the select#mobile
|| .on() method delegates events. Main advantage
|| of delegating events is that the event will
|| be registered not only for elements currently
|| in DOM, but elements that will be there in the
|| future.
*/
/* Callback function is getContent which is invoked
|| upon a change event occurring on #mobile
*/
$('#mobile').on('change', getContent);


function getContent(e) {
  // Store the value of a form control (i.e. #mobile)
  var opt = this.value;
  
  /* Pass value to a switch(). A switch() method is
  || a if/if else condition that's easier to read.
  */
  switch (opt) {
  
    // if (opt === 'android') {...
    case 'android':
    
      /* If getting/setting data of a form control
      || use .val() method.
      || ex. input, output, select, etc..
      */
      // Change the value of output#out
      $('#out').val(`Selected OS is Android`);
      
      /* If getting/setting content between an element's
      || tags use .html() or .text() methods
      || ex. <div>CONTENT</div>
      */
      // Change the HTML of section.dock
      $('.dock').html(
        `<h1>Samsung Galaxy</h1>
      <label>Model: <input></label>
      <button>DONE</button>`);
      break;
    case 'iOS':
      $('#out').val(`Selected OS is iOS`);
      $('.dock').html(
        `<h1>iPhone</h1>
      <label>Model: <input></label>
      <button>DONE</button>`);
      break;
      /* If its neither 'android' nor 'iOS', then it
      || refers to default case. In this particular case
      || output#out and section.dock will be erased. 
      */
    default:
      $('#out').val('');
      $('.dock').html('');
      break;
  }
}
select,
input,
button,
label {
  font: inherit
}
<form id='interface'>

  <select id='mobile'>
    <option value='-'>-------------</option>
    <option value='android'>Android</option>
    <option value='iOS'>iOS</option>
  </select>

  <output id='out'></output>
</form>



<section class='dock'></section>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 使用 if 语句和 jquery 更改 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45270659/

相关文章:

javascript - 如何仅当我将 javascript 元素悬停在我的 div 元素上时才显示它?

javascript最后一个if语句总是被读取

javascript - JavaScript 数组有问题吗?

javascript - 迷你任务流程栏

jquery如何获取页面当前屏幕顶部位置?

PHP:检测重复列结果的结尾(日历日)

sql-server - SQL 查询中的 IF 条件

javascript - 如何更改 highcharts 热图中单元格的颜色?

javascript - 选择没有两个或多个名称的表单

javascript - 单击按钮时动画 svg 矩形