ul导航-从onclick

时间:2019-01-10 12:36:57

标签: javascript

我有三个导航菜单。每个菜单都有许多参数。输入所有值后,我想保存它们。对于每个菜单,单击我都将调用“ checkMyFunction()”,然后尝试将其保存在localStorage中。完成后,我有“保存”按钮(此处未提供),可从localStorage创建一个json文件。

我的问题是:对于每个菜单单击,我想获取我没有得到的参数值“ val”,而是获取文件位置的整个路径。有人可以建议我吗?谢谢。

function checkMyFunction(val) {
	alert(val);
	if (val === 'one') {
		one();
	}
	else if (val === 'two') {
		two();
	}
	else if (val === 'three') {
		three();
	}
	else 
	{ 
		alert('not included yet');
	}
}
	
	
	
function one() {
		alert('this is function one related');
}


function two() {
		alert('this is function two related');
}


function three() {
		alert('this is function three related');
}
<!DOCTYPE html>
<html>
<head>
    <title>function check</title>

</head>

<script type="text/javascript" name="localObjectSave" src="localObjectSave.js"></script>

<body >
	
	<ul class="nav-icon">
		<li><a href="first.html" onclick="checkMyFunction(this,'first');">First Information</a></li>
		<li><a href="second.html" onclick="checkMyFunction(this,'second');">Second Information</a></li>
		<li><a href="third.html" onclick="checkMyFunction(this,'third');">third Information</a></li>
	</ul>
	
</body>

</html>

2 个答案:

答案 0 :(得分:1)

这仅仅是因为您仅传递了一个参数,并在代码中引用了错误的参数。这是行得通的。

const checkMyFunction = (e, val) => {
 val === 'first' ? one() : val === 'second' ? two() : val === 'third' ? three() : alert('not included yet');
}

	
const one = () => {
		alert('this is function one related');
}


const two = () => {
		alert('this is function two related');
}


const three = () => {
		alert('this is function three related');
}
<!DOCTYPE html>
<html>
<head>
    <title>function check</title>

</head>

<script type="text/javascript" name="localObjectSave" src="localObjectSave.js"></script>

<body >
	
	<ul class="nav-icon">
		<li><a href="first.html" onclick="checkMyFunction(this,'first');">First Information</a></li>
		<li><a href="second.html" onclick="checkMyFunction(this,'second');">Second Information</a></li>
		<li><a href="third.html" onclick="checkMyFunction(this,'third');">third Information</a></li>
	</ul>
	
</body>

</html>

答案 1 :(得分:0)

您只需在函数中添加一个新的“ obj”参数,然后将“ one”等条件更新为“ first”即可。

function checkMyFunction(obj, val) {
	alert(val);
	if (val === 'first') {
		one();
	}
	else if (val === 'second') {
		two();
	}
	else if (val === 'third') {
		three();
	}
	else 
	{ 
		alert('not included yet');
	}
}
	
	
	
function one() {
		alert('this is function one related');
}


function two() {
		alert('this is function two related');
}


function three() {
		alert('this is function three related');
}
<ul class="nav-icon">
		<li><a href="first.html" onclick="checkMyFunction(this,'first');">First Information</a></li>
		<li><a href="second.html" onclick="checkMyFunction(this,'second');">Second Information</a></li>
		<li><a href="third.html" onclick="checkMyFunction(this,'third');">third Information</a></li>
	</ul>

让我知道这是否对您有帮助。