[英]apply JavaScript to all elements with id
<a id="link" href="http://www.google.co.uk">link</a>
<a id="link" href="http://stackoverflow.com">link</a>
the javascript only replaces the first href
but i want it to apply to any and all <a>
with the id="link"
OR do you have a jQuery alternative? javascript只替换了第一个
href
但我希望它适用于任何和所有<a>
与id="link"
或者你有一个jQuery替代?
<script>
var link = document.getElementById('link');
var src = link.getAttribute('href');
var paramurl = encodeURIComponent(src);
link.setAttribute("href", "http://mysite.com/?url=" + paramurl);
</script>
Use a class-name instead of an id
: 使用类名而不是
id
:
<a class="link" href="http://www.google.co.uk">link</a>
<a class="link" href="http://stackoverflow.com">link</a>
With the JavaScript: 使用JavaScript:
var links = document.getElementsByClassName('link');
for (i=0;i<links.length;i++){
var src = links[i].getAttribute('href');
var paramurl = encodeURIComponent(src);
links[i].setAttribute('href','http://mysite.com/?url=' + paramurl);
/* or, preferably:
links[i].href = 'http://mysite.com/?url=' + paramurl;
*/
}
A complementary solution. 补充解决方案。 I have a table with many records (tr's), when I change the value with id="fecharendicion", the script changes all registers with the class="new_date".
我有一个包含许多记录(tr)的表,当我用id =“fecharendicion”更改值时,脚本会使用class =“new_date”更改所有寄存器。
<input id="fecharendicion" name="0" type="date" placeholder="dd/mm/yyyy" />
<script>
$(document.body).on('change','#fecharendicion', function() {
var fecha = $('#fecharendicion').val();
$('.new_date').val(fecha);
});
</script>
...
<tr>
<td><input name="{{a.first.id}}" type="date" class="form-control new_date" /></td>
</tr>
...
use classes instead 而是使用类
<a class="link" href="http://www.google.co.uk">link</a>
<a class="link" href="http://stackoverflow.com">link</a>
and change the href
attr like 并改变
href
attr
$("a.link").each(function(){
var src = $(this).attr("href");
var paramurl = encodeURIComponent(src);
$(this).attr("href","http://mysite.com/?url="+paramurl);
});
You should not have more than one element with the same id on a page. 您不应该在页面上具有多个具有相同ID的元素。 If you want to apply a javascript function to more than one element at the same time, you should use the class attribute.
如果要同时将javascript函数应用于多个元素,则应使用class属性。
The better is use classes, but with id can be: 使用类越好,但id可以是:
$(function () {
$('a[id=link]').each(function () {
var link = 'http://something' + $(this).attr('href');
$(this).attr('href', link);
});
});
use the jQuery $.each
method to apply changes to each separate <a>
tag. 使用jQuery
$.each
方法将更改应用于每个单独的<a>
标记。 Here is a working example: 这是一个工作示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.