我有一个链接,单击该链接后我想将标志变量的值设置为 1。这可能吗?喜欢
<a id='ctr' href='#' onclick='flag=1'> Hello </a>
以及如何在同一行上为 onclick 事件编写函数,例如代替
<a id='ctr' href='#' onclick='call_this();'> Hello </a>
function call_this(){
flag=1;
}
我可以在 onclick 行本身中使用 call_this 函数吗?
EDIT2
现在我有了这样的代码。在 onclick 事件中,值正确存储在 $selectedId 中。但是当我尝试在 url 中传递该值时,我没有得到正确的值。传递 for 循环中的最后一个值。
<script type="text/javascript">
$(document).ready(function(){
<?php foreach ($Forms as $r): ?>
$("<a id='<?php echo $ctr['Form']['id'];?> href='#' onclick='flag=1'> Hello </a>").appendTo("#header").click(function(){
<?php $selectedId=$r['Form']['id'];?>
alert("selId: "+<?php echo $selectedId;?>);//here the selected value is echoed
});
</script>
<a href="http://localhost/Example/new/export?height=220&width=350&id=<?php echo $selectedId;?>" class="thickbox button" title= "Export" >Export</a>
这里将 id 作为 4 传递,这是 php for 循环中的最后一个值。
最佳答案
由于 anchor 元素上有一个 ID,因此您可以轻松找到它并绑定(bind)事件。
如果这是一个简单的 Action ,您可以使用匿名函数,而不必在全局范围内声明一个函数:
window.onload = function () {
// Bind events...
document.getElementById('ctr').onclick = function () {
flag1 = 1;
return false; // stop the browser from following the link
};
// ....
};
编辑:查看您的编辑,页面加载时会触发 jQuery document.ready 事件,此时您标记的仍然是 null
。
请注意,您只是将 anchor 元素添加到 DOM,然后进行 if 语句。
因为您使用 jQuery,所以您可以使用它来绑定(bind) click事件到新创建的元素:
var flag=null;
$(document).ready(function(){
$('<a id="ctr" href="#"> Hello </a>').appendTo('#header').click(function () {
flag = 1;
e.preventDefault(); // stop the browser from following the link
});
});
您可以在 appendTo 之后执行此操作函数返回新创建的 DOM 元素,您可以直接将事件绑定(bind)到它。
关于javascript - 我可以在 onclick 函数中设置一个值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1332639/