最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - pass text to an onclick function - Stack Overflow

programmeradmin0浏览0评论

I want to pass text element (a string) to an on click function:

document.getElementById("struct_list").innerHTML="<li onClick='ClickStructList("+text+");'><a href='#'>"+text;`

ClickStructList is defined as follow:

ClickStructList=function(text){
window.alert("click");
window.alert(text);
};

This doesn't work, firefox debug istelling me: "C is not defined", C is the value of text.

Thanks for any help

PS: I do not want to use jquery

I want to pass text element (a string) to an on click function:

document.getElementById("struct_list").innerHTML="<li onClick='ClickStructList("+text+");'><a href='#'>"+text;`

ClickStructList is defined as follow:

ClickStructList=function(text){
window.alert("click");
window.alert(text);
};

This doesn't work, firefox debug istelling me: "C is not defined", C is the value of text.

Thanks for any help

PS: I do not want to use jquery

Share asked Jul 1, 2015 at 7:11 LaetisLaetis 1,3575 gold badges16 silver badges30 bronze badges 2
  • What doesn't work? The javascript code itself or when you click on the element? – nils Commented Jul 1, 2015 at 7:13
  • when I click nothing happen, if I remove the text argument it works, I get the "click" message. – Laetis Commented Jul 1, 2015 at 7:19
Add a ment  | 

4 Answers 4

Reset to default 2

Try to define your function as a function not variable

function ClickStructList(text){
   window.alert("click");
   window.alert(text);
};

Also when you define your onClick callback you should surround it by quotation

<li onClick='ClickStructList("My entered text");'>

so in your example:

.innerHTML="<li onClick='ClickStructList(\""+text+"\");'>

try by changing your JS code to this:

document.getElementById("struct_list").innerHTML="<li onClick='ClickStructList(\""+text+"\");'><a href='#'>"+text;

The quotation marks were missing in your call to ClickStructList ... this works :

 var ClickStructList=function (text) {
  window.alert("click");
  window.alert(text);
 };

 var text="Hello World";
 document.getElementById("struct_list").innerHTML="<li    
   onClick='ClickStructList(\""+text+"\");'><a href='#'>"+text;

you forgot to add the quote-signs for the string, so JS tries to parse your text as Code.

You need at least sth like this:

 ... "<li onClick='ClickStructList(\""+text+"\");'><a href='#'>" ...

or even better

 ... "<li onClick='ClickStructList("+ JSON.stringify(text) +");'><a href='#'>" ...
发布评论

评论列表(0)

  1. 暂无评论