我遇到一个问题,我需要将一个或多个参数传递给javascript
函数。例如
<a href="#" OnClick="Delete(1,'q');" > X </a>
<a href="#" OnClick="Delete(2,'u');" > X </a>
但是我试图从html端避免这个onclick
属性。所以我用这种方式
<a href="javascript://" title="Delete" id="actRemove" data-action="/List/Delete/1" ><span class="glyphicon glyphicon-remove"></span>Delete1</a>
<a href="javascript://" title="Delete" id="actRemove" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete2</a>
<a href="javascript://" title="Delete" id="actRemove" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete3</a>
并编写jQuery
这样的函数来从链接中捕获我的点击功能
$("#actRemove").each(function() {
$(this).on("click", function () {
alert($(this).data("action"));
});
});
但是唉!我没说了。此链接仅适用于第一个锚点Delete1
,没有任何锚点正在工作。这是我的jsFiddle链接。我已经完成了这些答案Q1,Q2,Q3,Q4,Q5,Q6。这些问题中的每一个都使用onclick
以第一种方式获得解决方案并将参数传递给函数。我的想法不同。此外,我的另一个问题是,有没有办法将参数传递给jQuery
function
而无需在onclick
属性中写html
?我知道jQuery函数能够接收参数,但是如何从html端将其发送到函数?
答案 0 :(得分:5)
而不是id
使用class
选择器: -
HTML: -
<a href="javascript:viod(0);" title="Delete" class="actRemove" data-action="/List/Delete/1" ><span class="glyphicon glyphicon-remove"></span>Delete1</a>
<a href="javascript:viod(0);" title="Delete" class="actRemove" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete2</a>
<a href="javascript:viod(0);" title="Delete" class="actRemove" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete3</a>
jQuery的: -
$(".actRemove").on("click", function () {
alert($(this).data("action"));
});
工作演示: -
$(".actRemove").on("click", function () {
alert($(this).data("action"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="javascript:viod(0);" title="Delete" class="actRemove" data-action="/List/Delete/1" ><span class="glyphicon glyphicon-remove"></span>Delete1</a>
<a href="javascript:viod(0);" title="Delete" class="actRemove" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete2</a>
<a href="javascript:viod(0);" title="Delete" class="actRemove" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete3</a>
注意: -
id
在jQuery中用作unique-selector
,而class
用作group-selector
答案 1 :(得分:2)
你可以这样使用
<a href="javascript://" title="Delete" id="actRemove_1" data-action="/List/Delete/1" ><span class="glyphicon glyphicon-remove"></span>Delete1</a>
<a href="javascript://" title="Delete" id="actRemove_2" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete2</a>
<a href="javascript://" title="Delete" id="actRemove_3" data-action="/List/Delete/2" ><span class="glyphicon glyphicon-remove"></span>Delete3</a>
$("a[id^='actRemove_']").on("click", function () {
alert($(this).data("action"));
})
答案 2 :(得分:1)
您可以直接在javascript中获取HTML对象的值,而无需使用onclick传递它:
var object_id = document.getElementById('object_id').value;