简体   繁体   中英

How to access value of clickable link in JavaScript or jQuery?

I am converting a string into a link dynamically using link() function. This link would open a JavaScript function which needs the value of link to write further logic. JavaScript function is getting called successfully but not able to capture the value of link.

I have checked "this" and "document" to locate the value but cannot see it. Also not able to capture clickable event.

I have an array ReqArr with below structure showing rows 0 to 5. I am showing it as a grid on webpage.

0: {Request_No: "1001", Request_State: "Draft", Owner: "ABC1"}
1: {Request_No: "1002", Request_State: "Closed", Owner: "ABC2"}
3: {Request_No: "1003", Request_State: "In Progress", Owner: "ABC3"}
4: {Request_No: "1004", Request_State: "Closed", Owner: "ABC4"}
5: {Request_No: "1005", Request_State: "Draft", Owner: "ABC5"}

I want to show request numbers as clickable links so that I can click it to check request details. I am accessing array as shown below and using link() function to insert anchor tags and href pointing to JavaScript function.

ReqArr[0].Request_No.link("javascript:openRequest()");

Output of above code is:

<a href="javascript:openRequest()">1001</a>

Function openRequest is getting called successfully when Request number 1001 is clicked. In this function, I will be using request number 1001 to write a logic to open the request 1001. However, I am not able to get the value 1001 in function. Could you please suggest how can I find the value?

You can listen to click event instead of calling inline function. In this case you link should like like

<a href="#" class="openRequest">1001</a>

And use something like this in your JS code:

$(function(){
 $('a.openRequest').click(function(event){
  event.preventDefault();
  var requestId = $(this).text();
  console.log(requestId);
  alert(requestId);
 });
});

To get value of a tag inside you openLink function, where this refers to current element.

Or simply put Request_No to function argument and use this argument.

ReqArr[0].Request_No.link("javascript:openRequest('"+ReqArr[0].Request_No+"')");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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