2 回答
TA贡献1829条经验 获得超6个赞
您只需要在外部声明变量即可使用它们。
var slug1 = "";
var slug2 = "";
function functionOne(e1) {
slug1 = e1.options[e1.selectedIndex].value;
}
function functionTwo(e2) {
slug2 = e2.options[e2.selectedIndex].value;
}
function submit() {
console.log(slug1);
console.log(slug2);
//window.location = 'https://example.com/' + slug1 + '-' + slug2;
}
<select onChange="functionOne(this);">
<option value="test1">Test One</option>
<option value="test2">Test 2</option>
</select>
<select onChange="functionTwo(this);">
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
</select>
<button id="submit" class="btn" type="button" onclick="submit();">Submit</button>
而且由于您要求更好的方式建议,您可以在提交时只使用一个功能,不会更好,也许只是更清洁。
例子:
function submit() {
var slug = [];
// create array
[...document.querySelectorAll("select")].forEach(sel => {
slug.push(sel.options[sel.selectedIndex].value);
// get values of each select and push into array
});
var link = 'https://example.com/' + slug[0] + '-' + slug[1]
// use array
//window.location = link
console.log(link);
}
<select>
<option value="test1">Test One</option>
<option value="test2">Test 2</option>
</select>
<select>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
</select>
<button id="submit" class="btn" type="button" onclick="submit();">Submit</button>
TA贡献1772条经验 获得超8个赞
您可以使您的slug1和slug2作为全局范围可访问var,以便能够在submit功能中使用它们。
此外,您还可以return从您的函数中获得functionOne一个。functionTwosubmit
现场演示:
var slug1
var slug2
//Change function
function functionOne(e1) {
slug1 = e1.options[e1.selectedIndex].value;
}
function functionTwo(e2) {
slug2 = e2.options[e2.selectedIndex].value;
}
//Submit
function submit() {
//window.location = 'https://example.com/' + slug1 + '-' + slug2);
let location = 'https://example.com/' + slug1 + '-' + slug2;
console.log(location) //https://example.com/test1-test1
}
<select onChange="functionOne(this);">
<option disbaled selected>Choose</option>
<option value="test1">Test One</option>
<option value="test2">Test 2</option>
</select>
<select onChange="functionTwo(this);">
<option disbaled selected>Choose</option>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
</select>
<button id="submit" class="btn" type="button" onclick="submit();">Submit</button>
添加回答
举报