简体   繁体   English

如何在<a>标记中</a>编写JavaScript代码

[英]how to write javascript code in <a> tag

I have a javascript variable soucreID and let us say 我有一个javascript变量soucreID,让我们说

sourceID = 10;

sourceID is dynamic value and always changes so i want to pass this to following tag sourceID是动态值,并且总是变化,因此我想将此传递给以下标记

<a href="edit-source.php?source=<script>document.write(sourceID)</script>">Edit</a>

But its not working, 但是它不起作用,

Can any one tell me how can i write javascript value in <a href=""> tag. 谁能告诉我如何在<a href="">标记中编写javascript值。

Thanks in Advance. 提前致谢。

Using jQuery, you could do this: 使用jQuery,您可以执行以下操作:

<a href="edit-source.php" class="edit-btn">Edit</a>
var id = 10;
var href = $(".edit-btn").prop("href");
$(".edit-btn").prop("href", href + "?source=" + id);

I assume you don't know the id before the code is rendered, otherwise this is rather moot. 我假设在渲染代码之前您不知道id ,否则这很无聊。

In Plain JS you can do 在Plain JS中,您可以执行

<script>
var souceID="somesource"; // this is of course assumed
document.write('<a href="edit-source.php?source='+sourceID+'">Edit</a>')
</script>

OR 要么

<a href="#" onclick="this.href='edit-source.php?source='+sourceID">Edit</a>

Using this code from a comment by the OP: 使用OP注释中的以下代码:

<div id="popuppage" data-role="popup" data-overlay-theme="a" style="max-width:250px;">    
  <ul data-role="listview" data-inset="true" data-dividertheme="d" data-theme="c" style="min-width:210px;"> 
    <li data-icon="gear" class="cust-popuplist" id="popupSourceID"> 
       <a href="#"
       onclick="
         this.href='edit-source.php?source='+
           encodeURIComponent(document.getElementById('srcvalue').value);
       ">Edit</a> 
       <input type="hidden" name="srcvalue" id="srcvalue" value="somevalue"> 
    </li> 
   </ul> 
</div>

Or how about this: No JS needed at all 还是这样:完全不需要JS

<form action="edit-source.php">
<input type="hidden" name="source" value="<?php echo $srcvalue; ?>" />
<input type="submit" value="Edit" />
</form>

You can't put tags inside of attribute values. 您不能将标签放在属性值内。

This is an ugly solution. 这是一个丑陋的解决方案。 And also that will work by dumping the variable out when the page first loads. 而且这也可以通过在页面首次加载时将变量转储出来而起作用。 If you had the variable then then you could just use PHP to insert it. 如果您有变量,则可以使用PHP插入它。

I'm guessing you want to respond to user input so the variable should be added to the link then. 我猜您想响应用户输入,因此该变量应随后添加到链接中。 You need an entirely different approach in which you set the entire href attribute at the proper time. 您需要一种完全不同的方法,您可以在适当的时候设置整个href属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM