如何将“ this”从元素传递到函数

时间:2019-12-19 01:24:31

标签: jquery

想干燥一些链接功能。非常基本的示例:

<p><a href="" data-href="Foo" class="link">Bar</a></p>

function Link() {
    var link = $(this).attr("data-href");
    alert(link);
}

$('.link').on('click',function(e){
    Link(this)
    e.preventDefault();
});

警报对话框返回'undefined'而不是data-href值。如何将点击处理程序中的值传递给函数?香港专业教育学院看了几个例子,似乎没有得到预期的效果。使用($(this))的变体似乎没有任何作用。

1 个答案:

答案 0 :(得分:2)

因此,只需将参数添加到函数链接:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get reference of widgets from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Build an AlertDialog
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                // Set a title for alert dialog
                builder.setTitle("Select your answer.");
                // Ask the final question
                builder.setMessage("Want to apply big font size?");
                // Set click listener for alert dialog buttons
                DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch(which){
                            case DialogInterface.BUTTON_POSITIVE:
                                // User clicked the Yes button
                                tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35);
                                break;
                            case DialogInterface.BUTTON_NEGATIVE:
                                // User clicked the No button
                                break;
                        }
                    }
                };
                // Set the alert dialog yes button click listener
                builder.setPositiveButton("Yes", dialogClickListener);
                // Set the alert dialog no button click listener
                builder.setNegativeButton("No",dialogClickListener);
                AlertDialog dialog = builder.create();
                // Display the alert dialog on interface
                dialog.show();
            }
        });
  }
}