所以我有这段代码,我觉得有一种方法可以不用if语句使用“ this”来执行此操作,但是我看不到解决方案。我试图获取单击按钮时发出警报的按钮的值。
<form>
<button id="cathetersize14" type="button" value = "14g" onclick="cath()">14g</button>
<button id="cathetersize16" type="button" value = "16g" onclick="cath()">16g</button>
<button id="cathetersize18" type="button" value = "18g" onclick="cath()">18g</button>
<button id="cathetersize20" type="button" value = "20g" onclick="cath()">20g</button>
<button id="cathetersize22" type="button" value = "22g" onclick="cath()">22g</button>
<button id="cathetersize24" type="button" value = "24g" onclick="cath()">24g</button>
function cath() {
var msg = document.getElementById("").value;
alert(msg);
}
</script>
答案 0 :(得分:1)
将该事件传递到onclick
回调中,并向cath
函数添加一个参数。然后,您可以访问如下所示的值:
function cath($event) {
var msg = $event.target.value;
alert(msg);
}
<button id="cathetersize14" type="button" value = "14g" onclick="cath(event)">14g</button>
答案 1 :(得分:1)
在以前的答案上稍作扩展,保持HTML演示文稿和JavaScript代码之间的分隔。
SELECT SCHEMA_NAME(schema_id) AS SchemaName,
name AS TableName,
OBJECTPROPERTY(OBJECT_ID, 'TableHasPrimaryKey') AS HasPrimaryKey,
OBJECTPROPERTY(OBJECT_ID, 'TableHasUniqueCnst') AS HasUniqueConstraint,
CASE
WHEN EXISTS (
SELECT *
FROM sys.indexes i
WHERE i.object_id = tables.object_id
AND is_unique = 1
)
THEN 1
ELSE 0
END AS HasUniqueIndex
FROM sys.tables
// Event handler for "cath" button click events
function cathHandler(event) {
console.log(event.target.value);
}
// Once all DOM elements have been created, attach event handlers
document.addEventListener("DOMContentLoaded", function() {
for (let button of document.getElementsByClassName("cath")) {
button.onclick = cathHandler;
}
});
答案 2 :(得分:0)
您将接收触发事件的元素的event.target作为参数。这样,您可以执行以下操作:
function cath(event) {
alert(event.target.value);
}
希望这是您要解决的问题!
答案 3 :(得分:0)
或者,您可以通过在JavaScript中选择按钮元素来消除html中的重复onclick
。您可以按标签选择,但是我为下面的示例在您的元素中添加了类名(假设页面上可能还有其他按钮元素)。
const buttons = document.getElementsByClassName('cathetersize');
for (let button of buttons) {
button.onclick = (event) => {
alert(event.target.value);
}
}
<form>
<button class="cathetersize" id="cathetersize14" type="button" value="14g">14g</button>
<button class="cathetersize" id="cathetersize16" type="button" value="16g">16g</button>
<button class="cathetersize" id="cathetersize18" type="button" value="18g">18g</button>
<button class="cathetersize" id="cathetersize20" type="button" value="20g">20g</button>
<button class="cathetersize" id="cathetersize22" type="button" value="22g">22g</button>
<button class="cathetersize" id="cathetersize24" type="button" value="24g">24g</button>
</form>