如何获得混合php和jQuery的“this”变量?

问题描述:

I have a set of boxes:

HTML

<button class="btn-modal">
   <div>Ajax content 1</div>
</button>
<button class="btn-modal">
   <div>Ajax content 1</div>
</button>

In the PHP loop I do:

<?php 
$permalink = get_permalink(); // Link of the box
?>
<script>
var simple = '<?php echo $permalink; ?>';
</script>

The php loop above prints the correct link for each box link in each simple variable

I then call the content via ajax like this:

$(document).on( 'click', ".btn-modal", function(){
  var cont = $(this).simple +  " .content"; // Load via ajax the Box link + content 
  jQuery(".modal-body").load(cont);
});

The variable simple is applied to all the boxes correctly but I am not getting this box link on click but I am getting a no found error instead

http://www.example.com/xchanges/home/work/interactive/undefined 404 (Not Found)

我有一组方框: p>

HTML p> \ n

 &lt; button class =“btn-modal”&gt; 
&lt; div&gt; Ajax内容1&lt; / div&gt; 
&lt; / button&gt; 
&lt; button class =“btn-modal  “&gt; 
&lt; div&gt; Ajax内容1&lt; / div&gt; 
&lt; / button&gt; 
  code>  pre> 
 
 

在PHP循环中我做: p>

 &lt;?php 
 $ permalink = get_permalink();  //方框的链接
?&gt; 
&lt; script&gt; 
var simple ='&lt;?php echo $ permalink;  ?&gt;'; 
&lt; / script&gt; 
  code>  pre> 
 
 

上面的php循环为每个简单 code>中的每个框链接打印正确的链接 变量 p>

然后我通过ajax调用内容,如下所示: p>

  $(document).on('click',“。btn  -modal“,function(){
 var cont = $(this).simple +”。content“; //通过ajax加载Box链接+内容
 jQuery(”。modal-body“)。load(cont  ); 
}); 
  code>  pre> 
 
 

变量 simple code>正确应用于所有框,但我没有得到 this 单击 code>上的框链接,但我找不到错误 p>

  http://www.example.com/xchanges/home/work/interactive/undefined  404(未找到)
  code>  pre> 
  div>

I guess i understand what you want to do. Your approach is not the correct way, you want to save a link for each div and then use that link in some JS logic.

Then in your loop (this is Wordpress right ?) you need to set out the link in the DOM element you want inside a data-attr and also give some class name to that div so that you can actually select it using JS

echo '<div class="someClass" data-src='. get_permalink() . '> ..... 

The result should be:

<div class="someClass" data-src="http://..." >Ajax content 1</div>

Now, your JS

$(document).on( 'click', ".btn-modal", function(){
  var cont = $(this).children('.someClass').attr('data-src') + " .content";
  jQuery(".modal-body").load(cont);
});