11548 sujets

JavaScript, DOM et API Web HTML5

salut

voila je vaudrai récupérer la valeur d'un lien sélectionné en js

<script type="text/javascript">
function bgproduit(arg) {

   var txt = document.getElementById(arg);
   alert(txt);
	}
</script>

<body>
<a id="liste1" href="#" onClick=bgproduit('liste1')>coco</a>
</body>

</html>


si j'utilise alert(txt) il m'affiche le chemin du code

et alert(txt.value()) n'affiche rien et le alert(txt.id ) affiche id
Bonjour,
function bgproduit (obj) {
    if (this.href)
        alert(this.href);
}
<a href="tonurl" onclick="bgproduit(this)">Lien</a>
Bonjour Gothor,

cela fonctionnera mieux, si tu utilises l'argument "obj" à la place de "this" :
"Gothor" a écrit :
function bgproduit (obj) {
if (obj.href)
alert(obj.href);
}
<a href="tonurl" onclick="bgproduit(this)">Lien</a>


@+
Modifié par Artemus24 (30 Apr 2012 - 13:27)
Bonjour new_dreams,

Cet exemple fonctionne parfaitement !

<!doctype html>
<html>
<head>
<title>Lire un Lien</title>
<script type="text/javascript">
function bgproduit (obj)
{
	if (obj.href)
		alert(obj.href);
}
</script>
</head>
<body>
<a href="http://www.google.fr/" onclick="bgproduit(this);">coco</a>
</body>
</html>


@+
Bonjour,

Pourquoi ne pas mettre d'emblée "this.href" comme argument, et laisser tomber les deux ".href" dans la fonction "bgproduit" ?
<a href="http://www.google.fr/" onclick="bgproduit(this.href);">coco</a>


Cordialement Smiley cligne
Je vois pas pourquoi transmettre un objet complet au lieu de la seule propriété dont on a besoin est plus simple ou plus efficace.

J'aurais dit exactement comme lddsoft :


<script>
function bgproduit(url) {
  alert(url);
  return false;
}
</script>
<a href="truc" onclick="return bgproduit(this.href);">lien</a>

Modifié par jb_gfx (03 May 2012 - 17:36)