如果有条件的内部字符串

时间:2019-10-04 02:28:24

标签: javascript jquery ionic-framework

我需要设置一个元素的innerhtml,但是代码的某些部分是有条件的。由于我无法追加到innerHtml,因此我想添加一个条件。我对JS还是很陌生,所以我找不到解决方法,因为我搞砸了“`”的标志。

我看到一些要附加到innerHtml的方法,但是我想要一种更简洁的方法

var arr = [10, 20, 30, 40]

func objectFromArr(at: Int) -> Int? {
    return at < 0 || at >= arr.count ? nil : arr[at]
}

2 个答案:

答案 0 :(得分:2)

一个选项正在使用conditional (ternary) operator,例如:

${
    foo === 1 ?                                       //Check if variable is one            
        '============= foo is 1 ============='        //If condition above is true              
    :           
        '============= foo NOT is 1 ============='    //If condition above is false
}

示例

let foo = 1;

let str = `
	Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
	Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
				
	    ${
	       foo === 1 ? 
					
	          '============= foo is 1 ============='
					
	       :
					
	          '============= foo NOT is 1 ============='
	    }
				
	Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
	Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
	`;

console.log(str);

答案 1 :(得分:0)

所以我不知道这会在多大程度上影响您的代码,这可能只是我的偏爱,但我认为使用的是单个tic(')vs严重字符(`)...所以我会用您的代码中的单个tic替换(坟墓)。然后继续,我相当确定您不能在javascript中使用php,(基于我非常原始的知识),首先,该网页运行php,生成html,然后将信息发送回客户端。 。由于javascript是在页面执行php后运行的,因此您不能将php代码放在已创建的html页面中,这是长话短说(就像烘烤蛋糕后,尝试添加鸡蛋来您忘了在开始时添加)。就使用javascript替换元素的“ innerHTML”而言,这相当容易。

    document.getElementById('my_element_id').innerHTML = '<!--inner contents-->';
    document.getElementsByClassName('my_elements_from_my_class')[0] = '<!--inner contents-->';
    /*NOTE: getElementsByClassName returns an array, in which you can index the elements by using [element number - the first element is 0]*/

希望这会有所帮助。