anson920520 anson920520 - 5 months ago 9x
HTML Question

JavaScript /Jquery : A for loop function with some special usage

This application have 2 components, a HTML page which contain some element and a JavaScript to generate buttons.

I will try to give out a simplify example in the question for now, but if there's something unclear then i would upload the full code later.

I am using HandleBar.js to generate different contents in the html but don't worry if you don't have any idea about this plugin i will make another non-handlebar.js version.

Consider the Html part looks like below:

HandleBar.js version

//{{feedId}} = 0t454g465754754h456
//{{url}} =

<div class="feedIdChecker">{{feedId}}</div>

<div class="{{feedId}}-EditRegionUrl" >{{url}}</div>

<button class="output-{{feedId}}"><a href="javascript:void(0)">Output</a></button>

Then i have a JQuery function which would output the url

var feedId = $(".feedIdChecker").html();

var postUrl = $('".'+feedId+'-EditRegionUrl"').html();
console.log(postUrl );

I found there's no way to identify which button is which. Since i need to declare the
var feedID
outside the button, it would always get the first feedID it founds and append to all buttons, how may i solve it? Please tell me if this question is confuse, i will try to explain it in a better way.

There's lots of people trying to help me but it seem i need to give out some more details in order for better understanding:


var initRegionEdit = function(){

var feedId = $(".feedIdChecker").html();
var postUrl = ($(this).prev('div').html());


<div class="EditRegionUrl" >{{url}}</div>
<div class="feedIdChecker">{{feedId}}</div>
{{#if region}}
<span class="dropdown"><i class="fa fa-map-marker" aria-hidden="true" style="color:gray;"></i>
<span class="result-date result-date-region" type="button" data-toggle="dropdown">{{region}}
<span class="caret"></span></span>
<ul class="dropdown-menu" style="min-width:100px;text-align:center;">
<li class="CTHK" data-url="{{url}}" style=" margin-top: 0px !important;margin-bottom: 0px !important;"><a href="javascript:void(0)">Hong Kong</a></li><div class="divider"></div>
<li class="CTTW" style=" margin-top: 0px !important;margin-bottom: 0px !important;"><a href="javascript:void(0)">Taiwan</a></li><div class="divider"></div>

I wish above information can help


So when you select $(".feedIdChecker") you actually get an array of all matching elements, but as soon as you call .html it only gets you the first. So to solve your issue we need to loop over all the $(".feedIdChecker")s like so:

$(".feedIdChecker").each(function(i, e) {
    var feedID = $(e).html();
        var postUrl = $("." + feedID + "-EditRegionUrl").html();

This will attach the click handler to each of the buttons.